Note on the use of Refs in react

In the class component:

Create Refs

Refs are  React.createRef() created using and  ref attached to React elements via attributes. When constructing a component, Refs are usually assigned to instance properties so that they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Visit Refs

When ref is passed to  render the element in , the reference to the node can  current be accessed in the ref's properties. 

const node = this.myRef.current;

In the function component:

Create Refs

 When used in function components, a refs should be created

const loginformRef = React.createRef();

Note: Be sure to create it before defining the component, otherwise you will not get current!

 Use Refs

Bind the objects that need to be used! 

 Visit Refs

It can be used through the method of loginformRef.current. Print out current to see!

 

Guess you like

Origin blog.csdn.net/weixin_45369856/article/details/128374853
Recommended