简体   繁体   English

ref回调如何在React中工作?

[英]How does the ref callback work in React?

The ref property enables us to capture the value of an uncontrolled component. ref属性使我们能够捕获不受控制的组件的值。

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? 想必input实际上是有一个属性(“托”),一个阵营组件ref认为需要时调用与现场的包装部件每当回调componentDidMount叫?

From the React documentation : React文档中

Adding a Ref to a DOM Element 向DOM元素添加引用

React supports a special attribute that you can attach to any component. React支持一个可以附加到任何组件的特殊属性。 The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted. ref属性具有回调函数,在挂载或卸载组件之后,将立即执行该回调。

[...] [...]

React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. 当组件安装时,React将使用DOM元素调用ref回调,而在卸载时使用null调用它。

So the ref callback is called after the component is mounted to the DOM, with the underlying DOM element as the sole argument. 因此,在将组件安装到DOM后,将调用ref回调,并将底层DOM元素作为唯一参数。 It is also called after unmounting with the argument null . 卸载后也会使用null参数调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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