作为链接https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute
然后它仅给出了立即使用该组件的示例。我试图找出如何使用此功能立即访问组件,并保存组件以供将来使用,正如我们所说的那样。
答案 0 :(得分:6)
区别在于使用ref = {callback} react将管理引用存储的责任传递给您。当你使用ref =" sometext"时,在封面下反应必须在你的类上创建一个refs属性,然后添加所有ref =" sometext"对它的陈述。
虽然很高兴有一个简单的this.refs.sometext访问组件,但是当组件被销毁时,反应方面很难清除这个refs属性。反应通过组件并让您处理或不处理它会更容易。
根据反应文件
当使用时,React将使用DOM元素调用ref回调 组件安装,并在卸载时调用它。
这实际上是一个非常灵活的想法,通过在卸载时传递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上设置的回调将接收该组件作为第一个参数,&#39; this&#39;单词将是当前班级的CustomTextInput&#39;在这个例子中。在回调中设置this.textInput将使textInput可用于所有其他函数,如focus()
Tweet显示了一个案例,其中ref回调更好用
答案 1 :(得分:2)
当您指定ref={callback}
之类的<input type="text" ref={(input) => {this.textInput = input}}/>
时,基本上您正在执行的操作是保存名称为textInput
的参考号以供将来使用。因此,我们可以使用回调方法,而不是使用ref="myInput"
然后使用this.refs.myInput
,然后像this.textInput
一样访问该组件。
以下是相同的演示,我们使用input value
上的ref
访问button click
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'));
&#13;
<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>
&#13;
答案 2 :(得分:0)
在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} />;
}
}