根据 fb 文档,this.props.children
是一个不透明的数据结构,不应直接操作。
事实上,文档说我们应该使用 React.Children
中的库函数。
看看库函数,它们都是 getter,这让我相信我们不应该改变 this.props.children
这是真的吗?我们可以改变 this.props.children
(例如动态插入组件等)吗?
谢谢!
最佳答案
您不能(或不应该)直接改变子级
。但是,您可以通过映射“修改”其输出:
const Hydrogen = props => (<div>{props.weight}</div>);
const Oxygen = props => (<div>{props.weight}</div>);
const Water = props => (
<div className='water'>
{React.Children.map(props.children, child => (
React.cloneElement(child, {
weight: props.weight / React.Children.count(props.children)
})
))}
</div>
);
const WaterBalloon = props => (
<div className='water-balloon'>
<Water weight={3}>
<Hydrogen />
<Hydrogen />
<Oxygen />
</Water>
</div>
);
在这里,我“修改”了传递给 Water 的子项,将重量属性传递给它们。
如果您需要“添加/删除”的能力,也许您应该考虑重新设计,维护一个“数据”数组,然后从该数据填充组件:
https://jsfiddle.net/814jze3z/
const Item = props => (
<li>{props.time}</li>
);
class List extends React.Component
{
constructor() {
super();
this.state = {
items: []
};
this.addItem = this.addItem.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addItem() {
let item = {
id: this.state.items.length + 1,
time: +new Date()
};
this.setState({
items: this.state.items.concat([item])
});
}
removeItem() {
this.setState({
items: this.state.items.concat().splice(1)
});
}
render() {
return (
<div>
<button onClick={this.addItem}>Add Item</button>
<button onClick={this.removeItem}>Remove Item</button>
<ul className='list'>
{this.state.items.map(item => (
<Item key={item.id} time={item.time} />
))}
</ul>
</div>
);
}
}
关于javascript - React - 你可以变异修改 this.props.children 来动态(以编程方式)添加子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809722/