Each child in an array or iterator should have a unique "key" prop.問題解決

var Button = React.createClass({
            //使用context時下級組件必須指定context的數據類型
           contextTypes:{
               color:React.PropTypes.string
           },
            render:function () {
                return (
                    <button style={{background: this.context.color}}>
                        {this.props.children}
                    </button>
                );
            }
        });

        var Message=React.createClass({
            render:function () {
                return (
                  <div>
                      {this.props.text} <Button>刪除</Button>
                  </div>
                );
            }
        });

        var MessageList=React.createClass({
            childContextTypes:{
                color:React.PropTypes.string
            },
            getChildContext:function () {
                return {color:"lightblue"}
            },
            render:function () {
                var i=0;
                var children=this.props.messages.map(function (message) {
                    return <Message key={'btn_'+(i++)} text={message}/>
                });
                return <div>{children}</div>;
            }
        });
        var messages=[
          "羅小黑",
          "諦聽",
          "老君"
        ];
        ReactDOM.render(
                <MessageList messages={messages}/>,
            document.getElementById('Context')
        );

錯誤主要意思是子組件缺少id屬性,因爲循環產生的子組件最好加上一個key屬性,那麼在定義父組件MessageList的時候,render函數中的<Message>組件要加上id屬性,如以上代碼標註的地方。

以上的代碼還有個知識點:使用Context特性實現組件樹上的數據越級傳遞,請仔細觀察標註的地方。

運行效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章