下面是我在 React Hooks 中的代码:
我有三个 React 功能组件 Parent、Child1、Child2。 我想单击 Child2 组件中的按钮,这应该调用父组件中的函数。如何实现这一目标?
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 />
}
最佳答案
下面的示例演示了如何通过组件传递事件。该示例非常简单,但如果您有任何疑问,请告诉我。
如果您不想处理“链接”事件,并且不想通过组件传递它们 - 您可以详细了解 Context API或React Redux ,因为它们都有状态和处理程序(又名 reducer )的“全局”概念。
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>
关于javascript - 如何使用 React Hooks 从子组件 onClick() 触发父组件中的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58571334/