【发布时间】:2018-07-29 00:52:46
【问题描述】:
您好,感谢您阅读此问题!
我已经学习 React 几个星期了,但我很难理解 refs 如何获取 React 的实例并将其放入 JS 变量中。
例如,我们可以讨论文档的示例:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 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 an instance field (for example, this.textInput).
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
我知道 ref 获取将被渲染的输入元素并使用 this.textInput 将其存储到类字段中。
但是我不明白为什么传递给 refs 的参数是(输入)如果嵌套了 jsx 标签会发生什么?例如两个输入?
还有没有明确的方法来引用使用 React 渲染/返回创建的元素?我说的是面向对象编程之类的东西:className.instanceName 或从 HTML 元素创建实例:new elementName()。
感谢您的帮助!
【问题讨论】:
标签: javascript reactjs