它的工作原理和行为相同,但想知道直接设置 ref 与通过以元素作为参数的回调设置它是否有任何实际差异。
给定这个反应钩子组件:
const myComponent = ({ ...props}) => {
const myRef = React.useRef(null);
...
return (
<div>
ref={myRef}
</div>
)
}
versus
const myComponent = ({ ...props}) => {
const myRef = React.useRef(null);
...
return (
<div>
ref={element => {
myRef.current = element;
}}
</div>
)
}
两者相似,根据useRef https://reactjs.org/docs/hooks-reference.html#useref docs:
useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传递的参数 (initialValue)。
因此,第一个代码示例的工作方式与第二个代码示例完全相同。
Except
如果您想在 React 将 ref 附加到 DOM 节点或从 DOM 节点分离时运行一些代码,您可能需要使用回调 ref。
意义;如果你想重新渲染组件,那么你可以使用回调引用。
最好的例子来自docs https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node itself:
测量 DOM 节点的位置或大小
function MeasureExample() {
const [height, setHeight] = useState(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<>
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</>
);
}
因此,您可以发现使用回调 ref 会改变元素的高度。如果您没有使用回调引用,那么它就不会被重新渲染,并且不会更新任何内容高度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)