[英]React: communicate between parent and child component
我想从我的子组件(输入表单)到我的父组件(弹出窗口)进行通信,天气或没有孩子中的任何数据。
我面临的问题是子组件不是它通过{props.children}
标签到达那里的代码中的集合子组件:
App.js 结构:
<div>
<Popup>
</Child>
</Popup>
</div>
Popup.js 结构:
<div>
{this.props.children}
</div>
有没有办法在不使用 window.* 变量或在我的 App.js 中使用 stateSet/stateRead function 的科学怪人?
我在这里做了一些冒险的事情,但它完成了工作:
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>
);
}
这是沙盒版本,可以看到它的实际效果: https://codesandbox.io/s/sad-wood-5kuit3?file=/NewApp.js
说明:
我打算做的是 append 来自父组件的孩子的道具。 为此,我将孩子们(由父母在 props 中接收)投射到本地 state。将 prop 附加到每个孩子以回调 function 与父母沟通。 Parent 组件现在返回具有修改/附加道具的 state 变量,而不是返回收到的 prop.children!
编辑:
正如所建议的那样,我已经使用 React.Children 来迭代父母在道具中收到的孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.