参考链接:https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
该文只提供了一个即时使用组件的示例。我想知道如何使用这个函数立即访问组件并保存组件以备将来使用,正如它所说我们可以做到的。
参考链接:https://reactjs.org/docs/refs-and-the-dom.html#callback-refs
该文只提供了一个即时使用组件的示例。我想知道如何使用这个函数立即访问组件并保存组件以备将来使用,正如它所说我们可以做到的。
使用ref={callback}的区别是,React将管理引用存储的责任交回给您。当您使用ref="sometext"时,在React内部,它必须在类上创建一个refs属性,并将所有ref="sometext"语句添加到其中。
虽然拥有一个简单的this.refs.sometext访问组件很好,但在React方面,清理这些refs属性时很困难且容易出错。让React将组件传递给您并让您处理是否要存储它会更容易。
根据React文档所述:
当组件挂载时,React将使用DOM元素调用ref回调函数,并在卸载组件时使用null调用它。
这实际上是一个非常巧妙的想法,通过在卸载时传递null并再次调用回调函数,您可以自动清除引用。
要实际使用它,您只需从任何函数中访问它,如下所示:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in this.textInput.
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}
您在 ref 上设置的回调函数将会接收组件作为第一个参数,在这个例子中,'this' 关键字将是当前类 'CustomTextInput'。在回调函数中设置 this.textInput 将可使 textInput 在其它所有函数中(如 focus())可用。
Dan Abermov 的推文 显示了一个使用 ref 回调函数更好的情况。
根据 Facebook 文档,使用字符串作为 refs 已被视为遗留 API,他们“建议改用回调模式或 createRef API。”
ref={callback}
,例如<input type="text" ref={(input) => {this.textInput = input}}/>
时,您实际上是将名称为textInput
的ref保存以备将来使用。因此,我们可以使用回调方法而不是使用ref="myInput"
,然后稍后访问组件,如this.textInput
,而不是使用this.refs.myInput
。按钮单击
上使用ref
访问输入值
的示例。
class App extends React.Component {
constructor(){
super();
}
handleClick = () => {
console.log(this.textInput.value);
}
render() {
return (
<div>
<input type="text" ref={(input) => {this.textInput = input}}/>
<button type="button" onClick={this.handleClick}>Click</button>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react-dom.min.js"></script>
<div id="app"></div>
在React 16.3中,您可以使用React.createRef()
API:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
ref = {(input) => {this.textInput = input;}}
- Felix Kling