gpt4 book ai didi

javascript - 使用回调分配 React ref 与直接设置它之间的区别?

转载 作者:行者123 更新时间:2023-11-29 15:57:38 26 4
gpt4 key购买 nike

它的工作原理和行为相同,但想知道直接设置 ref 与通过将元素作为参数的回调设置它是否存在任何实际差异。

给定这个 React 钩子(Hook)组件:

const myComponent = ({ ...props}) => {
const myRef = React.useRef(null);

...

return (
<div>
ref={myRef}
</div>
)
}

对比

const myComponent = ({ ...props}) => {
const myRef = React.useRef(null);

...

return (
<div>
ref={element => {
myRef.current = element;
}}
</div>
)
}

最佳答案

根据 useRef 两者相似文档:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).

因此,第一个代码示例将与第二个代码示例完全一样。

除了

If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

意义;如果你想重新渲染组件,那么你可以使用回调 ref。


来自 docs 的最佳示例本身:

测量 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 来更改。如果您没有使用回调引用,那么它就不会被重新渲染,也不会更新任何内容高度。

关于javascript - 使用回调分配 React ref 与直接设置它之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57204134/

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