When to use Refs Here are a few situations where Refs are appropriate:

  1. Manage focus, text selection or media playback.
  2. Trigger the forced animation.
  3. Integrate third-party DOM libraries.

There are three ways to use ref

  1. String (not recommended on the official website)
  2. The callback ref
class Demo extends React.Component{
  render () {
    return (
      <div>
        <input type="text" ref={el= >{ this.input1 = el}}></input>
        <button onClick={this.show}>Click on me to display data</button>
        <input type="text" onBlur={this.show2} ref={ el= > this.input2 = el}></input>
      </div>
    )
  }
  show = () = > {
    const { input1} = this
    alert(input1.value)
  }
  show2 = () = > {
    const { input2} = this
    alert(input2.value)
  }
}
Copy the code
  1. The React. CreateRef () to create
  • When the ref attribute is used for HTML elements, the ref created with react.createref () in the constructor receives the underlying DOM element as its current attribute.
  • When the REF attribute is used for a custom class component, the REF object receives the component’s mounted instance as its current attribute.
  • You cannot use the ref attribute on a function component.
class Test extends React.Component{
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render () {
    return (
      <div>
        <input type="text" onBlur={this.show} ref={ this.myRef} ></input>
      </div>
    )
  }
  show = () = > {
    const { myRef} = this
    alert(myRef.current.value)
  }
}

Copy the code