首页 > 解决方案 > 如何使用 React Hooks 从子组件 onClick() 触发父组件中的事件?

问题描述

下面是我在 React Hooks 中的代码:

我有三个 React 功能组件 Parent、Child1、Child2。我想单击 Child2 组件中的一个按钮,该按钮应该调用 Parent 组件中的一个函数。如何做到这一点?

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 />

}

标签: javascriptreactjs

解决方案


下面的示例演示了如何通过组件传递事件。该示例非常简单,但如果您有任何问题,请告诉我。

如果您不想处理“链接”事件,并且不得不通过组件传递它们 - 您可以更多地研究Context APIReact Redux,因为它们都有状态和处理程序(又名减速器)的“全局”概念.

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>


推荐阅读