在React中创建警报消息。

时间:2017-03-12 10:03:25

标签: javascript reactjs

我是React的新手,并设法写下一个有效的tic tac toe程序。如果用户输入正确的组合,我现在想要添加的是一条警告消息。

所以这是我的计划。

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor(props){
   super(props)

   this.state = {
       PLAYER_ONE_SYMBOL: "X",
       PLAYER_TWO_SYMBOL: "O",
       currentTurn: "X",
       board: [
        "", "", "", "", "", "", "", "", ""
       ]
   }
  }
  /*
   * @param index represents the position or index of each box
  */
  handleClick(index) {
    console.log(index);
    if(this.state.board[index] === "" && !this.state.winner) {
      this.state.board[index] = this.state.currentTurn
      this.setState({
        board: this.state.board,
        /* I am saying if the current turn is X change to 0 or change to X.   
 I use a turnary operator,as it is faster from if - else statements.  */  
        currentTurn: this.state.currentTurn === this.state.PLAYER_ONE_SYMBOL 
 ? this.state.PLAYER_TWO_SYMBOL : this.state.PLAYER_ONE_SYMBOL,
        winner: this.checkForWinner(),
      })
    }
 }
/*
A function that checks when the players wins. The logic is quite simple.    
First  I decrare the winning combination as an array.
Then I need to make sure the combination is not emtpy. And finally I am   
checking the combination.
*/   
checkForWinner() {
var currentTurn = this.state.currentTurn
var symbols = this.state.board
var winningCombos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7],   
[2, 5, 8], [0, 4, 8], [2, 4, 6]]
return winningCombos.find(function(combo) {
  if(symbols[combo[0]] !== "" && symbols[combo[1]] !== ""  &&   
symbols[combo[2]] !== ""  && symbols[combo[0]] === symbols[combo[1]] && 
symbols[combo[1]] === symbols[combo[2]]) {
    return currentTurn
  } else {
    return false
  }
})
}    
/* I am rendering whatever is on the board. */    
render() {
return (
  <div className="board">
      {this.state.board.map((cell,index) => {
        return <div onClick={() => this.handleClick(index)} 
className="square">{cell}</div>;   
      })}
  </div>
)
} 
}
export default App;

有关于此的任何想法吗?

谢谢,

西奥。

0 个答案:

没有答案