简体   繁体   中英

ReactJS call parent function from grandchild without using props

Hello I have a program right now where my great-grandchild calls the parent function that is passed down by props. I don't like the idea of passing a function too deep into the component tree. Is there an alternate way of doing this?

I looked into static functions, but I'm not sure how I can do it with functional components.

My component tree looks like this:

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

You can put a function into context just as you would put in a value.

Here is an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM