React@16.x(30)useImperativeHandle

作者 : admin 本文共844个字,预计阅读时间需要3分钟 发布时间: 2024-06-16 共1人阅读

目录

  • 1,介绍
  • 2,使用

1,介绍

在介绍 ref 时提到,ref 不能作用于函数组件,所以有了 ref 转发。

举例:

function Child(props, ref) {
    return <h1 ref={ref}>child</h1>;
}

const ChildWrap = React.forwardRef(Child);

export default function App() {
    const refChild = useRef();
    return (
        <>
            <ChildWrap ref={refChild}></ChildWrap>
            <button
                onClick={() => {
                    console.log(refChild.current);
                }}
            >
                获取Child组件
            </button>
        </>
    );
}

useImperativeHandle 的作用:在 ref 转发的前提下,为了更方便的在函数组件中使用 ref

2,使用

其他代码不变,只对子组件做如下修改:

function Child(props, ref) {
    useImperativeHandle(
        ref,
        () => {
            return 123; // 相当于 ref.current = 123
        },
        []
    );
    // 此时 h1 上的 ref 失效。
    return <h1 ref={ref}>child</h1>;
}

同样的,依赖项不变,该HOOK的回调函数不会再次执行。

此时在父组件中获取的 refChild.current 就是 123。
所以如果想通过父组件调用子组件的一些方法,可以将这些方法放到 useImperativeHandle 的第2个参数中即可:

function Child(props, ref) {
    useImperativeHandle(
        ref,
        () => {
            return {
                method1() {
                    console.log("method1");
                },
                method2() {
                    console.log("method2");
                },
            };
        },
        []
    );
    return <h1>child</h1>;
}

父组件调用:refChild.current.method1()


以上。

本站无任何商业行为
个人在线分享 » React@16.x(30)useImperativeHandle
E-->