React Hook 父子組件相互調用方法


1.子組件調用父組件函數方法

//父組件
let Father=()=>{
    let getInfo=()=>{
        
    }
    return ()=>{
        <div>
            <Children 
                getInfo={getInfo}
            />
        </div>
    }
}
//子組件
let Children=(param)=>{
    return ()=>{
        <div>
            <span onClick={param.getInfo}>調用父組件函數</span>
        </div>
    }
}

子組件調用父組件函數,可以向父組件傳參,刷新父組件信息

 

2.父組件條用子組件函數方法

//父組件
//需要引入useRef
import {useRef} from 'react'
let Father=()=>{
    const childRef=useRef();
    let onClick=()=>{
        childRef.current.getInfo();
    }
    return ()=>{
        <div>
            <Children 
                ref={childRef}
            />
            <span onClick={onClick}>調用子組件函數</span>
        </div>
    }
}
//子組件 
//需要引入useImperativeHandle,forwardRef
import {useImperativeHandle,forwardRef} from 'react'
let Children=(ref)=>{
    useImperativeHandle(ref, () => ({
        getInfo:()=>{
            //需要處理的數據
        }
    }))
    return ()=>{
        <div></div>
    }
}
Children = forwardRef(Children);

useImperativeHandle 需要配合着 forwardRef 使用,要不就會出現以下警告

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

  

 

 

 

參考:https://www.cnblogs.com/shine1234/p/13223391.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM