用react16写个井字棋demo

154 阅读1分钟

井字棋demo来源

react文档入门教程

react.html.cn/tutorial/tu…

踩坑

1、类组件中使用到this.props、this.state,一定要写constructor构造函数,并且在第一行调用super()

2、监听原生元素的点击事件   onClick={回调函数}

3、给组件传递属性    属性名={属性值}

4、在方法里修改state里面的数据后,使用setState()之后才会重新执行render方法,更新视图

5、如果要传递函数类型的属性给组件,那么必须传递这个函数的引用,或者箭头函数里调用这个方法

6、组件名必须首字母大写

7、函数式组件

函数式组件的应用场景,没有自己的state,只接受props。并返回一个组件(使用了JSX)

function Square(props) {
    return (
      <button className="square" onClick={props.onClick} >
        {props.value}
      </button>
    );
}

8、最好不要直接修改state的数据,而是创建一个副本

游戏组件

class Game extends React.Component {
  constructor(){
    super()
    this.state={
      history:[{
        squares:Array(9).fill(null)
      }],
      xIsNext: true
    }
  }
  handleClick(i){
    const history = this.state.history.slice()
    const current = history[history.length - 1]
    const squares = current.squares
    squares[i] = this.state.xIsNext ? 'X' : 'O'
    console.log(squares)
    this.setState({
      history,
      xIsNext: !this.state.xIsNext
    })
  }
  render() {
    const history = this.state.history.slice()
    const current = history[history.length - 1]
    const squares = current.squares
    return (
      <div className="game">
        <div className="game-board">
          <Board squares={squares} onClick={(i)=>this.handleClick(i)} />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

棋盘组件

class Board extends React.Component {
  constructor(){
    super();
  }
  renderSquare(i) {
    
    return <Square value={this.props.squares[i]} onClick={()=>this.props.onClick(i)} />;
  }
  render() {
    const status = 'Next player: X';
    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

棋盘方格组件

class Square extends React.Component {
  constructor(){
    super()
  }
  render() {
    return (
      <button className="square" onClick={this.props.onClick} >
        {this.props.value}
      </button>
    );
  }
}

计算赢家方法

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

渲染组件

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);