簡體   English   中英

ReactJS 從孫子調用父 function 不使用道具

[英]ReactJS call parent function from grandchild without using props

你好,我現在有一個程序,我的曾孫調用父 function,它是由道具傳遞下來的。 我不喜歡將 function 傳遞到組件樹太深的想法。 有沒有另一種方法可以做到這一點?

我查看了 static 功能,但我不確定如何使用功能組件來做到這一點。

我的組件樹如下所示:

App
- resetDisplay() //pass this down
- NavBar
  - ButtonGroup
    - ResetButton 
      - onClick = props.resetDisplay

您可以像輸入值一樣將 function 放入上下文中。

這是一個例子:

import React, {useContext} from 'react';

const NavbarContext = React.createContext({resetDisplay: () => {}});

function Navbar() {
    function resetDisplay() {
        // do stuff in here
    }

    return (
        <NavbarContext.Provider value={{resetDisplay}}>
            <ButtonGroup />
        </NavbarContext.Provider>
    );
}


function ButtonGroup() {
    return (
        <div>
            <ResetButton />
        </div>
    );
}

function ResetButton() {
    const {resetDisplay} = useContext(NavbarContext);

    return <Button onClick={() => resetDisplay()} >Reset</Button>;
}

暫無
暫無

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

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