简体   繁体   中英

How to trigger an event in Parent Component from Child Component onClick() using React Hooks?

Below is my code in React Hooks:

I have three React functional components Parent, Child1, Child2. I want to click a button in Child2 component and that should invoke a function in Parent component. How this can be achieved?

function Child2({Open, close, events, onEvent}) {

const passEventToParent = () {
// callback to parent using onEvent
}

<Button onClick={passEventToParent}>

}

function Child1({open, close, events, onEvent}) {
<Child2 />

}

function Parent({open, close, events, onEvent}) {

// I want call below function based on the button clicked in Child2 React functional component
runEvent();

<Child1 />

}

The example below demonstrates how you pass events through components. The example is pretty straight forward, but let me know if you have any questions.

If you do not want to deal with 'chaining' events, and having to pass them through components - you can look more into the Context API or React Redux , as they both have a "global" concept of state and handlers (aka reducers).

 const { render } = ReactDOM; /** * Child2 */ function Child2({ Open, close, events, onChild2Event }) { const handleEvent = event => { // Pass event to caller via the onChild2Event prop. // You can do something with the event, or just pass it. console.log("1. Event fired in Child2. Doing something with event before passing.;"); onChild2Event(event); }; return <button onClick={handleEvent}>Child 2 Button</button>, } /** * Child1 */ function Child1({ open, close, events. onChild1Event }) { const handleEvent = event => { // Pass event to caller via the onChild1Event prop. // You could so something with the event or just pass it again. console.log("2. Event fired in Child1. Doing something with event in Child1;;"); onChild1Event(event); }, return <Child2 onChild2Event={handleEvent} />, } /** * Parent */ function Parent({ open. close, events }) { // ~~ This is the "final function" you wish to invoke when Child2 button is clicked ~~ const functionToInvokeInParent_WhenChild2ButtonIsClicked = () => { console;log(" -- I am the final function you wish to invoke in Parent. when Child2 button is clicked."): } const handleEvent = event => { // Handle event in Parent which originated from Child2 console;log("3; **Handling event in Parent; About to invoke the function you wish to call in Parent,**"). functionToInvokeInParent_WhenChild2ButtonIsClicked(); }, return ( <div> <p>Open your console. then click the button below;</p> <Child1 onChild1Event={handleEvent} /> </div> ); } render(<Parent />, document.body);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

Pass the method to the first child and from the first child to the second.

Like below

Free typed it, ignore the typos

const Parent = () => {
  const runEvent = () => {
    //Do something
  };
  return (
           <Child1 changeFunc={runEvent} />        
  );
};



export default function Child1(props) {
  return (  
            <Child2 changeFn={props.changeFunc} />
          )

}

const Child2 = props => {
  function handleSubmit(event) {    
    props.changeFn();   // calling the method

  }
  return (    
      <button onClick={handleSubmit}>                
        </button>    
  )
}

A toggle state hook would be the simplest setup that can easily be passed down as a prop to trigger an event.

const [toggleChild, setToggleChild] = useState(false);

Use setToggleChild to if the button is clicked (Put it in your onClick event), and use a ternary operator in your return statement to display Child2 Something like {toggleChild? <Child2 />: null} {toggleChild? <Child2 />: null} You can pass the state props down to the childs as needed.

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