From 25e1f58939d1b19f197de17505c90d856b06c0b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=98=8E=E6=98=8E?= Date: Tue, 16 Feb 2021 18:04:23 +0800 Subject: [PATCH] =?UTF-8?q?[=E6=96=B0=E5=A2=9E]=E6=96=B0=E5=A2=9E=E4=BA=95?= =?UTF-8?q?=E5=AD=97=E6=A3=8B=E4=B8=96=E9=97=B4=E6=97=85=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.js | 91 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 57 insertions(+), 34 deletions(-) diff --git a/src/index.js b/src/index.js index 5825f82..7241e74 100644 --- a/src/index.js +++ b/src/index.js @@ -37,45 +37,16 @@ const Square = (props) => { } class Board extends React.Component { - // 类组件es6的constructor钩子函数 - constructor (props) { - super(props); - this.state = { - squares: Array(9).fill(null), - xInNext: true - } - } - // 定一个一个组件方法 - handleClick(i) { - // Array.slice()返回数组选定的元素,相当于克隆了原有数组 - const squares = this.state.squares.slice() - if(calculateWinner(squares) || squares[i]) { - return - } - squares[i] = this.state.xInNext ? 'X': 'O' - this.setState({ - squares, - xInNext: !this.state.xInNext - }) - } // 小方格方法 renderSquare(i) { return this.handleClick(i)} + value={this.props.squares[i]} + onSquare={()=>this.props.onBoard(i)} />; } render() { - const winner = calculateWinner(this.state.squares) - let status; - if (winner) { - status = '恭喜选手' + winner + '获胜~' - }else{ - status = '下一位选手: ' + (this.state.xInNext ? 'X': 'O'); - } return (
-
{status}
{this.renderSquare(0)} {this.renderSquare(1)} @@ -97,15 +68,67 @@ class Board extends React.Component { } class Game extends React.Component { + constructor (props) { + super(props) + this.state = { + history: [{ + squares: Array(9).fill(null) + }], + xIsNext: true, + stepIndex: 0 + } + } + // 定一个一个组件方法 + handleClick(i) { + const history = this.state.history.slice(0, this.state.stepIndex + 1) + const current = history[history.length - 1] + const squares = current.squares.slice() + if(calculateWinner(squares) || squares[i]){ + return + } + squares[i] = this.state.xInNext ? 'X': 'O' + this.setState({ + history: history.concat([{ squares }]), + xInNext: !this.state.xInNext, + stepIndex: history.length + }) + // Array.slice()返回数组选定的元素,相当于克隆了原有数组 + } + jumpTo(index){ + this.setState({ + stepIndex: index, + xIsNext: (index % 2) === 0, + }) + } render() { + const history = this.state.history + const current = history[this.state.stepIndex] + const winner = calculateWinner(current.squares) + const moves = history.map((stepArr, index) => { + const desc = index ? '下一步' + index : '开始游戏' + return( +
  • + +
  • + ) + }) + let status; + if(winner){ + status = '恭喜选手' + winner + '获胜~' + }else{ + status = '下一位选手: ' + (this.state.xInNext ? 'X': 'O'); + } return (
    - + this.handleClick(i)} + />
    -
    {/* status */}
    -
      {/* TODO */}
    +
    {status}
    +
      {moves}
    );