【问题标题】:ReactJS call parent function from grandchild without using propsReactJS 从孙子调用父函数而不使用道具
【发布时间】:2021-03-12 22:59:27
【问题描述】:

您好,我现在有一个程序,我的曾孙调用由 props 传递的父函数。我不喜欢将函数传递得太深到组件树中的想法。有没有其他方法可以做到这一点?

我研究了静态函数,但我不确定如何使用函数组件来实现。

我的组件树如下所示:

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

【问题讨论】:

  • 谢谢!这就是我要找的
  • edit:我研究了使用上下文,但我不确定如何在这种情况下应用它。如何创建一个以 resetDisplay() 作为其功能的上下文? @阿尔班博士

标签: javascript reactjs parent-child react-props react-functional-component


【解决方案1】:

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

这是一个例子:

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

【讨论】:

    猜你喜欢
    • 2018-09-04
    • 2015-08-12
    • 1970-01-01
    • 2019-07-27
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    相关资源
    最近更新 更多