useImperativeHandle 和 useRef 有什么区别?

iam*_*ynq 5 javascript reactjs react-hooks

据我了解,useImperativeHandle帮助父组件能够调用其子组件的函数。您可以在下面看到一个简单的示例

const Parent = () => {
    const ref = useRef(null);
    const onClick = () => ref.current.focus();

    return <>
        <button onClick={onClick} />
        <FancyInput ref={ref} />
    </>
}

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
      focus: () => {
        inputRef.current.focus();
      }
    }));
    return <input ref={inputRef} />;
}

FancyInput = forwardRef(FancyInput);
Run Code Online (Sandbox Code Playgroud)

但仅使用它就可以轻松实现useRef

const Parent = () => {
    const ref = useRef({});
    const onClick = () => ref.current.focus();

    return <>
        <button onClick={onClick} />
        <FancyInput ref={ref} />
    </>
}

function FancyInput(props, ref) {
    const inputRef = useRef();
    useEffect(() => {
        ref.current.focus = inputRef.current.focus
    }, [])
    return <input ref={inputRef} />;
}

FancyInput = forwardRef(FancyInput);
Run Code Online (Sandbox Code Playgroud)

那么真正的目的是什么useImperativeHandle。有人可以给我一些建议吗?谢谢

Dre*_*ese 3

useMemo可能类似于和useCallbackwhere之间的关系useCallback(fn, deps)相当于useMemo(() => fn, deps)。有时实现目标的方法不止一种。

我想说的是,useImperativeHandle代码可以更简洁/干一些当您需要公开多个属性时,

例子:

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    property,
    anotherProperty,
    ... etc ...
  }), []); // use appropriate dependencies

  ...
}
Run Code Online (Sandbox Code Playgroud)

function FancyInput(props, ref) {
  const inputRef = useRef();
  useEffect(() => {
    ref.current.focus = inputRef.current.focus;
    ref.current.property = property;
    ref.current.anotherProperty = anotherProperty;
    ... etc ...
  }, []); // use appropriate dependencies

  ...
}
Run Code Online (Sandbox Code Playgroud)

区别不大,但useImperativeHandle代码更少。

  • 小评论:`useImperativeHandle`也有一个依赖数组,所以你必须从`useEffect`中删除`[]`以使它们相似(除非没有其他差异) (2认同)