美文网首页
react-hooks使用ref进行父子组件通信

react-hooks使用ref进行父子组件通信

作者: Poppy11 | 来源:发表于2021-06-09 13:35 被阅读0次

    子组件

    import {useState, useImperativeHandle,forwardRef} from 'react';
     
    // props子组件中需要接受ref
    let ChildComp = (props,ref) => {
        // 此处注意useImperativeHandle方法的的第一个参数是目标元素的ref引用
        useImperativeHandle(ref, () => ({
            // changeVal 就是暴露给父组件的方法
            changeVal: (newVal) => {           
     
            }
        }));
        return (
            <div>{val}</div>
        )
    }
     
    ChildComp = forwardRef(ChildComp)
    

    父组件

    
    /* FComp 父组件 */
     
    import {useRef} from 'react';
     
    const FComp = () => {
     
        const childRef = useRef();
        const updateChildState = () => {
            // changeVal就是子组件暴露给父组件的方法
            childRef.current.changeVal(99);
        }
     
        return (
            <>
                <ChildComp ref={childRef} />
                <button onClick={updateChildState}>触发子组件方法</button>
            </>
        )
    }
    

    相关文章

      网友评论

          本文标题:react-hooks使用ref进行父子组件通信

          本文链接:https://www.haomeiwen.com/subject/wdmnsltx.html