javascript - 如何使用 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 />
}
解决方案
下面的示例演示了如何通过组件传递事件。该示例非常简单,但如果您有任何问题,请告诉我。
如果您不想处理“链接”事件,并且不得不通过组件传递它们 - 您可以更多地研究Context API或React 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>
推荐阅读
- html - SVG G Path Not Displaying
- css - 居中输入的文本[type=button]
- arrays - 如何访问嵌套的 json 对象?| 在 Laravel 电子商务项目中显示订单]
- sql - SQL 中的 PIVOT 给出错误 - ORA-00933: SQL 命令未正确结束
- python - 如何从位于不同目录中的另一个 python 文件执行 python 文件
- python - 用beautifulsoup从天才歌词中获取歌曲歌词│python 3.8
- azure - 将不同结构的文档存储在同一个 Azure COSMOS DB 容器中
- amazon-web-services - 什么是增强型 Vpc 路由的 Redshift 参数
- cmake - CMake:调用自定义命令作为 make install 的一部分
- ringcentral - 在 RingCentral 检查语音邮件不同的分机