计数从总回合中获胜

时间:2017-10-19 16:43:11

标签: javascript reactjs

目前每当我点击GameOfChance组件中的按钮时,它都会告诉我的表达式是真还是假。在状态我设置我的计数0和每次点击+ 1.我的问题是我如何计算胜利?现在它告诉我Expression没有定义。我怎么能告诉我的状态,当表达式为真或假时,它应该算+1或保持不变?

class Results extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
            <div>
                {
                    this.props.fiftyFifty ? 'You win!' : 'You lose!'
                }
            </div>
        )
    }
}  

class GameOfChance extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            count: 0,
            wins: 0,
            losses: 0
        }
    }

    increment = () => {
        this.setState({
            count: this.state.count + 1,
            wins: {expression} == true ? this.state.wins + 1 : this.state.wins
        })
    }


    render(){
        const expression = Math.random() > .5;
        return(
            <div>
                <button onClick={this.increment}>Gamble</button>
                <h1><Results fiftyFifty={expression} /></h1>
                <p>Total turns : {this.state.count}</p>
                <p>Wins: {this.state.wins}</p>
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:0)

您需要将随机数的结果传递给增量函数,如此

const Results = ({didWin}) => (didWin ? 'You win!' : 'You lose!')  

class GameOfChance extends React.Component{

    state = {
        count: 0,
        wins: 0,
        losses: 0
    }

    increment = (didWin) => (clickEvent) => {
        this.setState({
            count: this.state.count + 1,
            wins: didWin ? this.state.wins + 1 : this.state.wins
        })
    }


    render(){
        const didWin = Math.random() > .5;
        return(
            <div>
                <button onClick={this.increment(didWin)}>Gamble</button>
                <h1><Results didWin={didWin} /></h1>
                <p>Total turns : {this.state.count}</p>
                <p>Wins: {this.state.wins}</p>
            </div>
        )
    }
}