【问题标题】:Tic tac toe React井字游戏反应
【发布时间】:2017-05-10 22:47:58
【问题描述】:

我有两个组件。 家长:

    export default class GameBoard extends React.Component{
      constructor(props){
        super(props);
        this.state={
          boardPattern:[
            ' ',' ',' ',
            ' ',' ',' ',
            ' ',' ',' '
          ],
          turn: "",
          winner: null
        }
      }

        handleClick(i){
        console.log(i);
        this.state.board[i]=this.state.turn
        this.setState({
          board:this.state.board,
          turn: this.state.turn==='./images/x.ico'?'./images/y.ico':'./images/x.ico'
        })
  }
  render() {
    return (
      <div>

          {this.state.board.map(function(value, i){
            return <Square key={i} turn={this.state.turn} onChange={()=>this.handleClick(i)}/>
          }.bind(this))}
      </div>
          )
    }
  }

孩子:

export default class Square extends React.Component{
  handleClick = e => {
      if ( typeof this.props.onTurnChange === 'function'){
          this.props.onChange();
      }
  };
  render(){
    return <div className='Square' onClick={this.handleTurnChange}>
      <img src={this.props.turn}></img>
    </div>
  }
}

我对 handleClick 功能有疑问。现在,当我单击每个方块时,每个方块中的状态“转”(添加源图像)都会发生变化。我怎样才能使我点击的 Square 中只出现图像?

【问题讨论】:

    标签: reactjs tic-tac-toe


    【解决方案1】:

    好吧,我认为问题是你不能这样做this.state.board[i]=this.state.turn 不使用 setState 就无法设置状态值。

    尝试复制板子,更新它并使用新值设置状态

    类似的东西

    const updatedBoard = this.state.board.slice();
    updatedBoard[i] = this.state.turn;
    this.setState({board: updatedBoard});
    

    在您的示例中,我没有看到板的初始化位置?我只看到棋盘的图案处于不应该改变的状态。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-12
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      相关资源
      最近更新 更多