它的工作原理和行为都是一样的,但想知道直接设置ref与通过以元素作为参数的回调设置它有什么实际区别。
考虑到这一反应挂钩组件:
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>
)
}发布于 2019-07-25 14:24:47
这两个文档都类似于useRef文档:
useRef返回一个可变的ref对象,该对象的.current属性初始化为传递的参数(initialValue)。
因此,第一个代码示例的工作原理与第二个代码示例完全一样。
例外
如果您希望在反应、连接或分离ref到DOM节点时运行一些代码,则可能需要使用回调引用。
意思是:如果您想重新呈现组件,那么可以使用回调引用。
来自文档本身的最佳示例:
来度量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>
</>
);
}因此,您可以通过使用回调引用来发现元素的高度将被更改。如果您没有使用回调引用,那么就不会重新呈现它,也不会更新任何内容高度。
发布于 2019-07-25 14:26:40
好吧,使用第一种方法,您不能在内容更改时通知,突变.current属性不会重新呈现它,但是使用callback ref时,您可以根据用例运行一些代码,当React连接或分离一个ref到DOM节点时。
对于回调方法,您实际上不需要使用useRef,而是可以使用useCallback。以下是React文档中的一个示例:
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>
</>
);
}https://stackoverflow.com/questions/57204134
复制相似问题