reactjs - 动态附加组件
问题描述
我尝试动态附加一个组件,这里是我尝试添加到 MainComponent 的 Boards。当循环for运行时,函数 addChild 工作并且列表板正在填满,但没有发生任何其他事情,屏幕上没有显示任何内容
const MainComponent = props => (
<div className={props.className}>
<p>
<a href="#" onClick={props.addChild}>Add Another Child Component</a>
</p>
{props.boards}
</div>
);
class MainPage extends React.Component {
state = {
numChildren: 0
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
render () {
const boards = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
var _id = "board-" + i;
console.log
boards.push(<Board id={_id} className="board" />);
};
return (
<div className="test">
<Title/>
<MainComponent addChild={this.onAddChild} className="flexbox">
{boards}
</MainComponent>
</div>
);
}
}
export default MainPage```
解决方案
尝试为每个添加密钥ChildComponent
const boards = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
var _id = "board-" + i;
console.log
boards.push(<Board id={_id} key={_id} className="board" />);
};
因为 react 依赖于渲染在循环内渲染的组件的键
所以 react 认为你渲染的所有子元素都是一个组件,除非你给他们一个不同的键
推荐阅读
- nsis - 如何读入字节数组文件内容,然后更新它们并写入另一个文件?
- python - 如何使用 VGG19 keras 等前 10 层预训练模型?
- forms - 以批量形式使用 Pagerfanta/非 ArrayAccess 列表
- php - 删除帖子而不加载页面 - symfony4
- python-3.x - 使用图像处理将每个形状的颜色更改为独特的颜色
- xml - 如何使用 xmlstarlet 搜索和编辑与条件匹配的 xml 标记
- javascript - Apps 脚本自定义模式对话框中的 window.print()
- python - 将值插入多级索引数据帧
- php - 无法从继承方法中的子类访问私有变量
- javascript - Shopify Slate 模板 JS 文件中未调用的函数