文档中提供的示例如下:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
据我所知,我可以用
function FancyInput(props, ref) {
const inputRef = useRef();
useEffect(() => {
if (ref) {
ref.current = {
focus: () => {
inputRef.current.focus();
}
};
}
}, [ref]);
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
useImperativeHandle 不太冗长的可能解释对我来说似乎太微不足道了。引擎盖下是什么?是什么使它比 useEffect 版本必要或更好?
最佳答案
TLDR; 和useImperativeHandle
是一样的只处理所有 ref
案例并确保传递的值是 ref 而不仅仅是任何值。
回答您的问题 它为您处理使用 refs 时所需的一切,因此它节省了一些代码。
我在看 source code钩子(Hook)和引擎盖下的样子,useImperativeHandle
与您使用 useEffect
的方法几乎相同.
你可以看一下钩子(Hook),看看它们有一个 HooksDispatcherOnMount , HooksDispatcherOnUpdate和 HooksDispatcherOnRerender .
如果您查看关联的函数(fooImperativeHandle
和 fooEffect
),您会发现它们都调用相同的函数(fooEffectImpl
)。
所以很明显,在引擎盖下,它是同一件事,但在使用 useImperativeHandle
时你不需要处理.current
的部分,它已经检查了 null
值,检查它是否是 ref
并在 .current
中设置返回值如您所见here .
这是我查看源代码得到的,但如果我错了,请纠正我。
关于javascript - 与在 useEffect 中分配转发的 ref 相比,useImperativeHandle 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860956/