[英]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 withnull
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.