React Series (1)- Scaffolding creation project React Series (2)- React Basics React Series (4)- React Lifecycle

React, like Vue, doesn’t need to manipulate DOM elements in most cases. Just focus on the state of the component, and use setState to update the state so that the page UI is updated. But there are special cases where you need to manipulate the DOM. Such as:

  1. Handles focus, text selection, and media control
  2. Trigger forced animation
  3. Integrate third-party DOM libraries

ref

React provides this property, if ref is set to native HTML, to get the DOM element; If set to a component, it gets an instance of the component. ComponentWillMount = componentDidMount = componentWillMount = first render = componentDidMount = componentDidMount

  1. String binding (not recommended, may be deprecated later)
import React from 'react';

class App extends React.Component {
    
    // componentDidMount is a lifecycle function called after the page has been rendered
    componentDidMount() {
        console.log(this.refs.content) // 
      
Hello, World!
} render() { return ( <div ref="content">Hello, World!</div>)}}export default App; Copy the code

Results:

  1. Callback function form (recommended)
import React from 'react';

class App extends React.Component {
    
    componentDidMount() {
        console.log(this.content) // 
      
Hello, callback!
} render() { return ( <div ref={e= > this.content = e}>Hello, callback!</div>)}}export default App; Copy the code

Results:

  1. CreateRef () (Latest approach)
import React from 'react';

class App extends React.Component {

    constructor(props) {
        super(props);
        this.content = React.createRef();
    }
    
    componentDidMount() {
        // The current attribute is used to get the DOM element
        console.log(this.content.current) // 
      
Hello, Wrold!
} render() { return ( <div ref={e= > this.content = e}>Hello, Wrold!</div>)}}Copy the code

Results:

ForwardRef Gets the child component instance

import React from 'react';

const Test = React.forwardRef((props,ref) = >{
  return (
      <div ref={ref}>{props.txt}</div>)})class App extends React.Component {

  constructor(props) {
    super(props)
    this.content = React.createRef()
  }

  componentDidMount() {
    console.log(this.content.current)  test 
  }

  render() {
    return (
      <div>
        <Test ref={this.content} txt="Test" />
      </div>)}}export default App;
Copy the code

Results:

Add styles to elements

import React from 'react';

class App extends React.Component {

    constructor(props) {
        this.content = React.createRef();
    }
    
    componentDidMount() {
        // Set the background color
        this.content.style.background = 'red'
    }
    render() {
        return (
            <div ref={e= > this.content = e}></div>)}}Copy the code