2016-08-25 37 views
1

我不認爲我完全理解父/子關係如何在React中工作。我有兩個組件,ColumnSpace。當呈現Column時,它創建一些Spaces。我認爲這意味着Column將是那些Spaces的父母,但是我錯了,或者我錯誤地使用了React.Children.count(this.props.children)的某個部分 - 它總是告訴我,任何給定的Column有0個孩子。從父組件訪問子項的狀態?

簡化模型:

var Column = React.createClass({ 
    getInitialState: function() { 
     return {childCount: '', magicNumber: this.props.magicNumber}; 
    }, 
    componentDidMount: function() { 
     var newCount = React.Children.count(this.props.children); 
     this.setState({childCount: newCount}); 
    }, 
    render: function() { 
     return (
      <div className='Column'> 
       { 
        Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>) 
       } 
      </div> 

     ); 
    } 
}); 

var Space = React.createClass({ 
    render: function() { 
     return (
      <div className="Space"> 
       space here 
      </div> 
     ); 
    } 
}); 

好像無論我在ColumnReact.children.count(this.props.children),它告訴我有0孩子。我期望示例代碼中生成的Column有五個子項,因爲其中創建了五個Space

我想也許我是想算兒童,他們完全加載之前,所以我試着寫一個單擊處理程序是這樣的:

//in Column 
setChildCount: function() { 
    var newCount = React.Children.count(this.props.children); 
    this.setState({childCount: newCount}); 
} 

然後在我Column加入這樣一個按鈕:

... 
render: function() { 
     return (
      <div className='Column'> 
       { 
        Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>) 
       } 
      <button onClick={this.setChildCount} /> 
      {this.state.childCount} 
      </div> 
     ); 

但我的childCount永遠是永遠0.任何人都可以看到我要去哪裏錯了嗎?

編輯:最終,我希望得到所有在其狀態設置爲Y值的X屬性的所有子元素的計數,但我顯然距離這一點還有一步或三步。

回答

1

Column組件在該代碼上沒有任何子組件。兒童是由父組件包裝的組件。所以,想象一下:

<Column> 
<Space/> 
<Space/> 
<Column/> 

在這種情況下,父親Column有兩個孩子Space

在你的代碼:

 <div className='Column'> 
      { 
       Array.from({ length: this.state.magicNumber }, (x,y) => <Space key={y}/>) 
      } 
     </div> 

你正在創建不是組件內div內新組件Column

+0

好的,我明白了。是否有可能讓組件像我想在這裏那樣「渲染」自己的孩子,或者這種事情只能在「ReactDOM.render」中正常工作?很抱歉,如果這太偏離了OP。 – souldeux

+0

在反應教程中閱讀父級子女術語的邏輯;)https://facebook.github.io/react/docs/multiple-components。html – LuisPinto

+0

哈哈,謝謝 - 這確實回答了我的問題 – souldeux

1

您正在渲染Space組件作爲的一部分組件。通過this.props.children捕獲的父/子關係是這樣的:

var Column = React.createClass({ 
    render: function() { 
    <div className="column"> 
     {this.props.children} 
    </div> 
    } 
}); 

ReactDOM.render(
    <Column> 
    <Space /> //little space children 
    <Space /> 
    </Column> 
); 

要獲取您的具體問題,你不需要什麼樣this.props.children,因爲你在你的渲染方法具有的一切權利那裏。

所以你的問題的答案是:應用與渲染時相同的邏輯。