我不認爲我完全理解父/子關係如何在React中工作。我有兩個組件,Column
和Space
。當呈現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>
);
}
});
好像無論我在Column
把React.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屬性的所有子元素的計數,但我顯然距離這一點還有一步或三步。
好的,我明白了。是否有可能讓組件像我想在這裏那樣「渲染」自己的孩子,或者這種事情只能在「ReactDOM.render」中正常工作?很抱歉,如果這太偏離了OP。 – souldeux
在反應教程中閱讀父級子女術語的邏輯;)https://facebook.github.io/react/docs/multiple-components。html – LuisPinto
哈哈,謝謝 - 這確實回答了我的問題 – souldeux