簡體   English   中英

React 16:使用鈎子和功能組件時,從父級調用子級的 function

[英]React 16: Call children's function from parent when using hooks and functional component

我需要在他們的父組件中調用孩子的 function 。 我該怎么做? 以前在 React 15 中,我可以使用 refs 來調用 children 的 function。 但是不知道如何使用鈎子和功能組件來做到這一點。

function Child(props) {
    function validate() {
        // to validate this component
    }

    return (
        <>Some code here</>
    )
}


function Parent(props) {
    const refs = useRef([]);
    const someData = [1,2,3,4,5];

    function validateChildren() {
        refs.current.forEach(child => {
            child.current.validate(); // throw error!! can not get validate function
        });
    }

    return (
        <>
            <button onClick={validateChildren}>Validate</button>
            {
                someData.map((data, index) => {
                    return <Child ref={ins => refs.current[index] = ins} />
                })
            }
        </>
    )
}

我的實際要求是: 1. 可以添加多個選項卡,根據用戶的行為刪除 2. 單擊選項卡父級中的按鈕觸發驗證 3. 所有選項卡都需要自行驗證,在其選項卡中顯示錯誤消息並返回驗證消息

您可以將useImperativeHandleforwardRef一起使用。

文檔中,

useImperativeHandle自定義使用 ref 時暴露給父組件的實例值。 與往常一樣,在大多數情況下應避免使用 refs 的命令式代碼。 useImperativeHandle應該與forwardRef一起使用

const Child = React.forwardRef((props,ref) => {

    //validate will be available to parent component using ref
    useImperativeHandle(ref, () => ({
      validate() {
        // to validate this component
        console.log("I'm clicked");
      }
    }));

    return (
        <>Some code here</>
    )
})

在父組件中,您可以訪問子 function 為,

function validateChildren() {
   refs.current.forEach(child => {
      child.validate(); // you can access child method here 
   });
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM