2016-03-03 30 views
1

我有一個組件,我正在使用的組件有一個列表,如果其上的項目被單擊,將輸出與該項目相關的某些數據。該反應類的樣子:在React.js中分離出組件

SocialMenu = React.createClass({ 

    getInitialState: function(){ 
     return { focused: 0 }; 
    }, 

    clicked: function(index){ 

     // The click handler will update the state with 
     // the index of the focused menu entry 

     this.setState({focused: index}); 
    }, 

    render: function() { 

     // Here we will read the items property, which was passed 
     // as an attribute when the component was created 

     var self = this; 

     // The map method will loop over the array of menu entries, 
     // and will return a new array with <li> elements. 

     return (
      <div> 
       <ul className="testblocks">{ this.props.items.map(function(m, index){ 

        var style = ''; 

        if(self.state.focused == index){ 
         style = 'focused'; 
        } 

        // Notice the use of the bind() method. It makes the 
        // index available to the clicked function: 

        return <li key={index} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>; 

       }) } 

       </ul> 

       <p>Selected: {this.props.items[this.state.focused]}</p> 

      </div> 
     ); 

    } 
}); 

編輯:

組件是這樣的,我想:

ItemDetails = React.createClass({ 

    render: function() { 

     return (
      <div>{this.props.item}</div> 
     ); 
    } 

}); 

,當我把它放在SocialMenu組件這工作得很好,但是如果我想把它放在頁面的其他地方,輸出是不確定的。我如何處理這個問題?

編輯:

我想如此這般在這樣的組件來進行設置:

Description = React.createClass({ 

    getInitialState: function() { 
     return { default: true }; 
    }, 

    render: function() { 

     return (

      <section id="one" className="main style1"> 
       <div className="container"> 

        <ItemDetails /> 

        <span className="image fit"> 
         <img src="images/pic01.jpg" alt="" /> 
        </span> 

       </div> 
      </section> 

     ); 

    } 

}); 

<ItemDetails />組件應顯示關聯於點擊特定項目相關的輸出在SocialMenu的列表中。如果我只是餵它的道具(<ItemDetails items={['items', 'some more'}/>),它只會打印它餵食的東西。

如果我把SocialMenu放在描述組件中,那麼列表就顯示在那個部分(我不想)。

+0

只是...然後創建另一個組件?你有什麼麻煩? – azium

+0

如何獲取該組件繼承: – user1072337

+0

{this.props.items [this.state.focused]} – user1072337

回答

1

您可以將此代碼移動到將當前項目作爲道具的新組件。

你已經獲得通過this.props.items[this.state.focused]目前的項目,以便通過這爲道具,以新組件

<ItemDetails item={ this.props.items[this.state.focused] } />

+0

我該如何編寫ItemDetails組件? – user1072337

+0

所以,我創建了組件,但是我不能將它放在另一個組件(另一個部分)中,因爲它沒有提供項目數據。錯誤是:Uncaught TypeError:無法讀取未定義的屬性'undefined' – user1072337

0

有非常好的article通過關於 丹阿布拉莫夫(終極版的作者) 分離展示和容器組件