Javascript ReactJS在不使用道具的情况下从孙子调用父函数

Javascript ReactJS在不使用道具的情况下从孙子调用父函数,javascript,reactjs,parent-child,react-props,react-functional-component,Javascript,Reactjs,Parent Child,React Props,React Functional Component,您好,我现在有一个程序,我的曾孙调用由道具传递的父函数。我不喜欢在组件树中传递太深的函数。有其他的方法吗 我研究了静态函数,但不确定如何使用功能组件 我的组件树如下所示: App - resetDisplay() //pass this down - NavBar - ButtonGroup - ResetButton - onClick = props.resetDisplay 您可以将函数放入上下文,就像放入值一样 以下是一个例子: import React, {

您好,我现在有一个程序,我的曾孙调用由道具传递的父函数。我不喜欢在组件树中传递太深的函数。有其他的方法吗

我研究了静态函数,但不确定如何使用功能组件

我的组件树如下所示:

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

您可以将函数放入上下文,就像放入值一样

以下是一个例子:

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>;
}

import React,{useContext}来自“React”;
const NavbarContext=React.createContext({resetDisplay:()=>{});
函数Navbar(){
函数resetDisplay(){
//在这里做事
}
返回(
);
}
函数按钮组(){
返回(
);
}
函数ResetButton(){
const{resetDisplay}=useContext(NavbarContext);
返回resetDisplay()}>Reset;
}

请看这里,谢谢!这就是我正在寻找的foredit:我研究了如何使用上下文,但我不确定如何在这种情况下应用它。如何创建以resetDisplay()为函数的上下文@阿尔班博士