[英]React: communicate between parent and child component
I want to communicate from my Child component (a input form) to my parent component (popup) weather or not there is any data in the child.我想从我的子组件(输入表单)到我的父组件(弹出窗口)进行通信,天气或没有孩子中的任何数据。
The issue im facing is that the child component isn't a set child in the code it gets there with the {props.children}
tag:我面临的问题是子组件不是它通过
{props.children}
标签到达那里的代码中的集合子组件:
App.js structure: App.js 结构:
<div>
<Popup>
</Child>
</Popup>
</div>
Popup.js structure: Popup.js 结构:
<div>
{this.props.children}
</div>
Is there a way to do this without using a window.* variable or frankenstein-ing a stateSet/stateRead function in my App.js?有没有办法在不使用 window.* 变量或在我的 App.js 中使用 stateSet/stateRead function 的科学怪人?
I have done some risky stuff here, but it gets the job done:我在这里做了一些冒险的事情,但它完成了工作:
import React, { useEffect, useState } from "react";
export default function NewApp() {
return (
<Parent pProps="boss">
<Child text="Hello1" />
<Child text="Hello2" />
<Child text="Hello3" />
</Parent>
);
}
function Parent(props) {
const [children, setChildren] = useState([]);
function communicateWithMe(val) {
console.log("I am called", val);
}
useEffect(() => {
let _children = React.Children.map(props.children, (child) => {
console.log("Parent child", child);
return {
...child,
props: {
...child.props,
callBack: communicateWithMe
}
};
});
console.log("_children", _children);
setChildren(_children);
}, []);
return (
<div
style={{
background: "black",
color: "white"
}}
>
{children}
</div>
);
}
function Child(props) {
console.log(props);
return (
<div>
<p>{props.text}</p>
{props.callBack && (
<button
onClick={() => {
props.callBack("children baby");
}}
>
invoke Parent function
</button>
)}
</div>
);
}
here is the sandbox version to see it in action: https://codesandbox.io/s/sad-wood-5kuit3?file=/NewApp.js这是沙盒版本,可以看到它的实际效果: https://codesandbox.io/s/sad-wood-5kuit3?file=/NewApp.js
Explaination:说明:
What I aimed to do was to append the props on the children from the parent component.我打算做的是 append 来自父组件的孩子的道具。 To do that, I casted the children (received in props by Parent) in to local state. Appended the prop to each child to have a callback function to communicate with the parent.
为此,我将孩子们(由父母在 props 中接收)投射到本地 state。将 prop 附加到每个孩子以回调 function 与父母沟通。 The Parent component now returns the state variable that has the modified / appended props, instead of returns prop.children as it received!
Parent 组件现在返回具有修改/附加道具的 state 变量,而不是返回收到的 prop.children!
EDIT:编辑:
As suggested, I have used React.Children to iterate over the children recieved by the parent in props.正如所建议的那样,我已经使用 React.Children 来迭代父母在道具中收到的孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.