2016-09-20 4 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, мой друг! Спасибо:) –