Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Refs concept

Refs provides a way to access DOM nodes or React elements created in the Render method.

String refs

The easiest way to use refs is to use String refs directly: , this.refs.input1.

As can be seen from the official website, this type of String refs is outdated and not recommended.

Refs in the form of callback functions

React will call the ref callback and pass in the DOM element when the component is mounted and null when it is unmounted. React ensures that the refs are up to date before componentDidMount or componentDidUpdate is triggered.

class Demo extends React.Component {
  showInfo = () = > {
    const { input } = this;
    console.log(input.value);
  }
  saveInput = (c) = > {
    this.input = c;
    console.log(The '@', c);
  }
  render() {
    return(
      <input ref={this.saveInput} type="text" /><br/><br/>
      <button onClick={this.showInfo}>Click my prompt for input</button>)}}Copy the code

The ref callback, defined as an inline function, is executed twice during the update process, once passing in null (to clear the old ref) and once passing in the DOM element (to set the new ref). If you use a binding function, the update is executed once and the DOM element is passed in.

In practice, the ref callback function of the inline function will be used more often because it is more convenient. Although it will be executed twice during the update process, it will not have much impact in most cases.

The use of createRef

The react. createRef call returns a container that can store the nodes identified by ref. The container can store only one node, i.e., “dedicated”.

class MyComponent extends React.Component {
  myRef1 = React.createRef();
  myRef2 = React.createRef();
  
  showData1 = () = > {
    // The ref created with react.createref () receives the underlying DOM element as its current attribute.
    alert(this.myRef1.current.value);
  }
  
  showData2 = () = > {
    alert(this.myRef2.current.value);
  }
  
  render() {
    return(
      <input ref={this.myRef1} type="text" /><br/><br/>
      <button onClick={this.showData1}>Click my prompt for input</button>
      <input onBlur={this.showData2} ref={this.myRef2} type="text" /><br/><br/>); }}Copy the code

Don’t overuse Refs