您好,感谢您阅读此问题!
我已经学习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()。
谢谢您的帮助!
React支持可以附加到任何组件的特殊属性。该ref属性具有回调函数,并且callback将在安装或卸载组件后立即执行。
ref
callback
当你写
<input type="text" ref={(input) => { this.textInput = input; }} />
ref安装组件后,React提取属性并调用回调。在该回调函数中,react传递输入实例,这就是您在此处获得的参数。将以上内容视为功能
<input type="text" ref={this.callback} />
该回调看起来像
const callback = (input) => { this.textInput = input; }
根据文档:
在HTML元素上使用ref属性时,ref回调将接收基础DOM元素作为其参数。
关于下一个问题:
但是我不明白为什么传递给refs的参数是(输入)如果嵌套了jsx标签会发生什么
传递给DIV的参数为只是引用作为输入你的榜样,你可以调用它,你想要,就什么样input,inputRef,instance
input
inputRef
instance
在嵌套多个jsx标签的情况下,将ref应用于传递ref属性的元素上。例如
<div ref={this.getRef}> <div>Hello React</div> </div>
的ref获取实例将应用于外部div,您可以从中访问子元素。
密码箱
也没有一种明确的方法来引用使用React渲染/返回创建的元素
好吧,这refs是React提供的一种参考方法,用于创建元素。但是,您仅应在以下情况下使用引用
refs
大多数情况下,这props是父组件与子组件交互的唯一方式。要修改孩子,请使用新道具重新渲染它。例如,如果您希望更改元素上的类,而不是获得对该元素的访问权并更改它的类,则可以将动态道具传递给它,例如
props
<div className={this.props.className} />
或者事实上,用于state进行必要的更新
state