在 React 中转发引用和回调引用有什么区别?



根据 React.js 官方文档,下面的代码是回调引用的一个示例。

function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
componentDidMount(props) {
//Here, this.inputElement in Parent will be set to the DOM node corresponding to the element in the CustomTextInput
console.log(this.inputElement);
}
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}

在这里,Parent 中的this.inputElement将被设置为与CustomTextInput中的元素对应的 DOM 节点。

在转发参考的情况下,根据官方文件,

const FancyButton = React.forwardRef((props, ref) => {
return (
<button ref={ref} className="FancyButton" data-name="My button">
{props.children}
</button>
);
});
//Parent Component
class FancyButtonWrapper extends React.Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
componentDidMount(props) {
//Here this.ref will point to button element. Because of this reason, ref.current will give the value of button.
console.log(this.buttonRef.current.getAttribute("data-name"));
}
render() {
return (
//Here we are passing the ref to the child component.
<FancyButton ref={this.buttonRef} data-attr="Hello">
Click me!{" "}
</FancyButton>
);
}
}

在这里,在这种情况下,this.ref将指向按钮元素。由于这个原因,ref.current将给出按钮的值。

forwardRefcallbackRefs之间有什么区别吗?在这两种情况下,我们都可以从父节点访问子节点的引用。

我不是专家,但这里有一些事情需要考虑: - 当我们需要动态设置 refs 时,使用回调引用。 - 当需要访问子引用时,通常使用转发引用

好吧,使用转发参考回调引用之间的区别在于 HOC。

如果将 ref prop 传递给 HOC ,那么在 HOC 内部,您无法进一步将其传递给封闭组件(HOC 包装(,因为 props 属性不会将 ref 存储在其中。ref 不是键,请参阅此处:https://reactjs.org/docs/forwarding-refs.html

因此,除了这个用例之外,它们以相同的方式工作。 希望有帮助!!

不同之处在于在 ref 回调的情况下,您可以在 ref 更改时运行副作用。如果您使用useRef,您可以随时访问 ref,但您不知道何时设置它,或者运行将 ref 作为依赖项的useEffect

回调 refs 具有更多的控制权 - 例如,它们允许您在设置 ref 时设置状态,这将在组件挂载时重新渲染组件,并且您可以使用 ref 节点执行任何您需要的操作。

简而言之 - 通常使用useRef因为它是最简单的。但是 ref 回调可以在需要时为您提供更多控制权

最新更新