如何在React.js

时间:2016-08-14 22:21:18

标签: javascript reactjs ecmascript-6

我正在学习React.js,我不确定如何做到以下几点:

我有以下React类(为简单起见而删除)

const X01Game = React.createClass({


saveShot(e) {
    e.preventDefault();
    const currentPlayer = this.props.players[this.state.currentPlayer],
          currentID     = currentPlayer.ID,
          shot          = this.refs.shot.value;
       .... shot saved.....
},
isValidShot( shot ) {
    const currentPlayer = this.props.players[this.state.currentPlayer],
          currentID     = currentPlayer.ID,
          score         = this.state.score[currentID];
    .... shot validated.....
},

render() {

    return (
        <div className="game-container">
            .... render game ....
        </div>  
    );
}
});

export default X01Game;

正如你在几种方法中看到的那样,我重复一遍:

    const currentPlayer = this.props.players[this.state.currentPlayer],
      currentID     = currentPlayer.ID,
      shot          = this.refs.shot.value;

有什么方法可以全局声明这些,所以避免重复每个方法?这样看起来不适合我

1 个答案:

答案 0 :(得分:0)

由于您始终要求currentPlayerId,只需向X01Game class添加方法即可获得该方法:

getGurrentPlayerId() {
    var currentPlayer = this.props.players[this.state.currentPlayer];
    return currentPlayer ? currentPlayer.id : null; // in case the player doesn't exist
}

拍摄也是如此:

getShot() { // pun intended 
    return this.refs.shot && this.refs.shot.value;
}

现在你可以做到:

saveShot(e) {
    e.preventDefault();
    const currentID     = this.getGurrentPlayerId(),
          shot          = this.getShot();
       .... shot saved.....
},
isValidShot( shot ) {
    const currentID     = this.getGurrentPlayerId(),
          score         = this.state.score[currentID];
    .... shot validated.....
},