2016-11-20 46 views
0

我正在嘗試使樹形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}
但它沒有解決我該如何解決這個問題?

回答

1

的問題不在於你的父母組成部分,但與你的孩子的組件

這可能會解決這個問題:

root.addChild(<Person id="child1" key="child1" name="B" />); 
root.addChild(<Person id="child2" key="child2" name="C" />); 
root.addChild(<Person id="child3" key="child3" name="D" />); 

但在我看來,你正在接近一個非常糟糕的方式問題 - 你不應該保留整個渲染元素在你的state,只有數據需要渲染他們,然後在render你應該創建樹

+0

那麼添加孩子的最佳方式是什麼? –

+0

@WebEngine通過傳遞數據結構,例如。 '[{id:「child1」,name:「B」},{id:「child2」,name:「C」},{id:「child3」,name:「D」}]''在這個數據 – pwolaq

1

你的關鍵只需要是唯一的;爲什麼不把它設置爲值ID

root.addChild(<Person id="child1" key="child1" name="B" />); 
+0

OP說他做了,但似乎他已經把'key'放在錯誤的組件上 – pwolaq