最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

Below is my code in React Hooks:

I have three React functional ponents Parent, Child1, Child2. I want to click a button in Child2 ponent and that should invoke a function in Parent ponent. 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 ponent
runEvent();

<Child1 />

}

Below is my code in React Hooks:

I have three React functional ponents Parent, Child1, Child2. I want to click a button in Child2 ponent and that should invoke a function in Parent ponent. 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 ponent
runEvent();

<Child1 />

}
Share Improve this question asked Oct 26, 2019 at 13:45 VamsiVamsi 1491 gold badge3 silver badges13 bronze badges 2
  • Pass the function as prop to Child1 and get Child1 to pass it to Child2 – Agney Commented Oct 26, 2019 at 13:49
  • Passed onEvent to child1 and then child2, how can i call this in child2 based on onClick in child2 ? getting this error if i call onEvent in child2 : Uncaught TypeError: onEvent is not a function - but i validated onEvent as func proptype. – Vamsi Commented Oct 26, 2019 at 13:52
Add a ment  | 

3 Answers 3

Reset to default 8

The example below demonstrates how you pass events through ponents. 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 ponents - 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./ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./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} You can pass the state props down to the childs as needed.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论