2016-09-20 72 views
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') 
); 

回答

1

嘗試運動(「棒球」或「足球」)傳遞給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 
    }, 

應該更新相應的狀態。你也可以使用匿名函數,雖然他們會傷害很多孩子的表現。

這裏有一個小提琴:https://jsfiddle.net/69z2wepo/57095/

+0

你ROCK,我的朋友!非常感謝:) –