React.js-如何从父组件更新动态子组件的属性/道具/状态



所以我现在正在学习React,并试图开发自己的包。我遇到了这个问题。

所以我有一个父组件来控制子组件,但这些子组件没有明确定义。它们可通过props.children访问。

这可能是一个简单的例子来解释我的处境。我没有定义数量的子组件作为父组件的子组件。

function Parent(props) {
functionCalledEverySecond() {
for (let child of props.children) {
// Increment width by 1 like:
// child.props.width  += 1
}
}
return <div>{props.children}</div>;
}
function Child(props) {
return <div style={{ width: props.width }}></div>;
}

我该如何着手解决这个问题?

我建议您使用React.Children API(react children API)。您可以映射所有子项,使用React.cloneElement(child, {props})(react clone元素)克隆每个子项,然后设置新道具。

有一个链接和代码:

import React from "react";
import ReactDOM from "react-dom";
import { Grid, Row, Col } from "react-flexbox-grid";
function Parent(props) {
return React.Children.map(props.children, (child) => {
return React.cloneElement(child, {
width: parseInt(child.props.width) * 2 + "px"
});
});
}
function Child(props) {
return (
<div
style={{ width: props.width, height: "10px", background: "black" }}
></div>
);
}
class App extends React.Component {
render() {
return (
<Parent>
<Child width={"10px"} />
<Child width={"20px"} />
<Child width={"30px"} />
<Child width={"40px"} />
<Child width={"50px"} />
</Parent>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
<body>
<div id="container"></div>
</body>

最新更新