简体   繁体   中英

How does the ref callback work in React?

The ref property enables us to capture the value of an uncontrolled component.

class MyComponent extends Component {
  render() {
     <input type="text" ref={el => this.setState({ myEl: el })}/>
  }
}

How does this work? Presumably input is actually a React component that has a property ("prop") ref that takes a callback that is invoked with the wrapper component of the field every when componentDidMount is called?

From the React documentation :

Adding a Ref to a DOM Element

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

[...]

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

So the ref callback is called after the component is mounted to the DOM, with the underlying DOM element as the sole argument. It is also called after unmounting with the argument null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM