其他分享
首页 > 其他分享> > 2020-12-31

2020-12-31

作者:互联网

react hooks 父组件调用子组件的方法

/* child子组件 */

import {useState, useImperativeHandle} from 'react';

//props子组件中需要接受ref

const ChildComp = ({cRef}) => {

    const [val, setVal] = useState();

    // 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用

    useImperativeHandle(cRef, () => ({

        // changeVal 就是暴露给父组件的方法

        changeVal: (newVal) => {

          setVal(newVal);

        }

    }));

}

/* FComp 父组件 */

import {useRef} from 'react;

...

const FComp = () => {

    const childRef = useRef();

    const updateChildState = () => {

        // changeVal就是子组件暴露给父组件的方法

        childRef.current.changeVal(99);

    }

    ...

    return (

        <>

            {/* 此处注意需要将childRef通过props属性从父组件中传给自己 cRef={childRef} */}

            <ChildComp  cRef={childRef} />

            <button onClick={updateChildState}>触发子组件方法</button>

        </>

    )

}

标签:12,const,useImperativeHandle,31,react,2020,childRef,组件,changeVal
来源: https://blog.csdn.net/weixin_45492532/article/details/112018432