0
我試圖更新baseballIndex和footballIndex的狀態,以便它們可以獨立保持狀態而不必製作額外的組件。例如,當我更改footballIndex時,我不希望baseballIndex隨之改變。將密鑰傳遞爲Reactjs中的道具
問題是,當我傳遞道具時,子組件只能更新密鑰的屬性,而不能更新密鑰本身。
代碼如下,在這裏是對的jsfiddle鏈接:https://jsfiddle.net/reactjs/69z2wepo/
var Home = React.createClass({
getInitialState: function() {
return {
baseballIndex: 0,
footballIndex: 0
};
},
increaseIndex: function(index) {
this.setState({index: this.state.index +1})
},
render: function() {
return <div>
<Tut sport={'Basbeall'}
index={this.state.baseballIndex}
increaseIndex={this.increaseIndex}/>
<Tut sport={'Football'}
index={this.state.footballIndex}
increaseIndex={this.increaseIndex}/>
</div>
}
});
var Tut = React.createClass({
render: function() {
return <div>
<div>
{this.props.sport}:
{this.props.index}
</div>
<div style={{width: 30, height: 30, backgroundColor: 'red'}}
onClick={()=> {this.props.increaseIndex(this.props.index)}}>
</div>
</div>;
}
});
ReactDOM.render(
<Home/>,
document.getElementById('container')
);
你ROCK,我的朋友!非常感謝:) –