我正在嘗試使樹形HTML。 (帶反應)如何將鍵添加到React組件對象
這是節點類,它包含子節點。
class Node extends React.Component {
constructor(props) {
super(props);
this.state = {
children: []
};
}
render() {
return <div id={this.props.id} className="person">
<div className="info">
<div className="name">{this.props.name}</div>
</div>
<div className="childrenWrap">
<div className="children">
{this.state.children}
</div>
</div>
</div>;
}
addChild(node) {
this.setState({children: this.state.children.concat(node)});
}
}
//////////////
let tree = document.querySelector("#tree");
let root = ReactDom.render(<Person id="root" name="A" />, tree);
root.addChild(<Person id="child1" name="B" />);
root.addChild(<Person id="child2" name="C" />);
root.addChild(<Person id="child3" name="D" />);
但是,該代碼將出現警告「在數組中迭代每個孩子都應該有一個獨特的‘鑰匙’的道具。」。
所以我加了key={this.props.id}
旁邊的id={this.props.id}
。
但它沒有解決我該如何解決這個問題?
那麼添加孩子的最佳方式是什麼? –
@WebEngine通過傳遞數據結構,例如。 '[{id:「child1」,name:「B」},{id:「child2」,name:「C」},{id:「child3」,name:「D」}]''在這個數據 – pwolaq