React@16.x(30)useImperativeHandle

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()


以上。

  • 12
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下雪天的夏风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值