gpt4 book ai didi

reactjs - React 中的 ref={callback} 和 ref = "myInput"有什么区别?

转载 作者:行者123 更新时间:2023-12-03 13:16:32 25 4
gpt4 key购买 nike

as the link 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 will call the ref callback with the DOM element when thecomponent mounts, and call it with null when it unmounts.

这实际上是一个非常巧妙的想法,通过在卸载时传递 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()

具体示例

Tweet Dan Abermov 展示了 ref 回调效果更好的案例

enter image description here

更新

Facebook Docs使用字符串作为引用被认为是遗留问题,他们“建议使用回调模式或 createRef API。”

关于reactjs - React 中的 ref={callback} 和 ref = "myInput"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com