不知道我是否正確理解這一點。如果我正在創建一個子組件,請鍵入button,這會增加它自己的計數器,是否可以在沒有2個獨立函數的情況下執行此操作?以下我做的似乎是一個黑客?如果theres X按鈕數量,我將如何重構此代碼更加動態? REF的工作方式似乎可以引用孩子中的html,但其他方式呢?我是否甚至想過這是正確的方式,因爲組件有它自己的狀態,它是否應該有自己的更新方法?React - 更新每個子組件的狀態
/*** @jsx React.DOM */
var MyComponent = React.createClass({
getInitialState: function() {
return {
counter1: 1,
counter2: 1
};
},
increment: function(i) {
if (i === 1) {
this.setState({
counter1: this.state.counter1 + 1
});
} else {
this.setState({
counter2: this.state.counter2 + 1
});
}
},
render: function() {
return (<div>
<ChildComponent item = {this.state.counter1} click={this.increment.bind(this, 1)}/>
<ChildComponent item={this.state.counter2} click={this.increment.bind(this, 2)}/ >
< /div>
);
}
});
var ChildComponent = React.createClass({
render: function() {
return (
<div>
<h1> Counter {this.props.item} </h1 >
<button onClick = {this.props.click} > ++ < /button>
</div >
);
}
});
React.render(< MyComponent/> , document.body);
對不起,這個問題我不清楚。你正在談論的2個獨立功能的名稱是什麼? – nilgun 2015-02-07 18:08:47
如果每個孩子都有增量功能,即增量1和增量2,我想我已經解決了這個錯誤的方式。我認爲每個ChildComponent應該有它自己的增量函數。解決方案= https://gist.github.com/antigirl/90f46aa7f51ba05f676a ? – 2015-02-07 18:13:23