我正在尝试更新baseballIndex和footballIndex的状态,以便他们可以独立保持状态而无需制作额外的组件。例如,当我更改footballIndex时,我不希望baseballIndex随之改变。
问题是,当我传递道具时,子组件只能更新密钥的属性,而不能更新密钥本身。
代码如下,这里是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')
);
答案 0 :(得分:1)
尝试将运动(&#39;棒球&#39;或足球&#39;)传递给increaseIndex
功能而不是索引。例如,在<Tut>
:
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.sport)}}> <--- Change this!
</div>
</div>;
}
});
然后修改您的increaseIndex
功能:
increaseIndex: function(sport) {
var stateKey = sport.toLowerCase() + 'Index'; // transform into your state's key
var newState = _.cloneDeep(this.state); // copy the current state
newState[stateKey] = newState[stateKey] + 1 // increment the state with specific index
this.setState(newState) // update the state
},
它应该更新适当的状态。您也可以使用匿名函数,但在许多孩子的情况下它们会损害性能。