Стиль прохождения Reactjs работает, но не динамически? - PullRequest
0 голосов
/ 07 января 2019

Может показаться, что это повторяющийся вопрос, пожалуйста, помогите мне, потому что все, что я прочитал, не помогает: (

В эти дни я изучал React, не слишком грубо обращайтесь ко мне, я основываюсь на учебнике Tic Tac Toe с сайта React и расширил его до сетки 4x4 для большего удовольствия. Все как оригинальный урок.

Теперь я пытаюсь динамически установить синий цвет для X и красный для O, передав стиль в реквизите, который будет унаследован от класса Board функцией Square.

Работает, но цвет не меняется с красного ....

enter image description here

Любая помощь будет очень признательна.

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(16).fill(null)
        }
      ],
      xTurn: true,
      stepNumber: 0
    };
  }
  /**
   * goes to history state of game
   * @param  step - the move number
   */
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xTurn: step % 2 === 0
    });
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xTurn ? 'X' : 'O';
    this.setState({
      history: history.concat([
        {
          squares: squares
        }
      ]),
      stepNumber: history.length,
      xTurn: !this.state.xTurn
    });
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const desc = move ? 'Go to move #' + move : 'Go to start';
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player is ' + (this.state.xTurn ? 'X' : 'O');
    }

    return (
      <div className="game">
        <h1 className="title">JJBA 4 WAY TIC TAC TOE</h1>
        <div className="game-rules">
          Plays like regular game except that players can win three ways: 4
          corners, 4 in a square (anywhere on the board) or 4 in a row
          (vertical, horizontal, diagonal).
        </div>
        <br />
        <div className="game-container">
          <Board squares={current.squares} onClick={i => this.handleClick(i)} />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}
const xColor = { color: '#3ab3ab' };
const oColor = { color: 'red' };

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        style={this.props.xTurn ? xColor : oColor}
      />
    );
  }

  render() {
    return (
      <div className="game-board">
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
          {this.renderSquare(3)}
        </div>
        <div className="board-row">
          {this.renderSquare(4)}
          {this.renderSquare(5)}
          {this.renderSquare(6)}
          {this.renderSquare(7)}
        </div>
        <div className="board-row">
          {this.renderSquare(8)}
          {this.renderSquare(9)}
          {this.renderSquare(10)}
          {this.renderSquare(11)}
        </div>
        <div className="board-row">
          {this.renderSquare(12)}
          {this.renderSquare(13)}
          {this.renderSquare(14)}
          {this.renderSquare(15)}
        </div>
      </div>
    );
  }
}

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

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

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

1 Ответ

0 голосов
/ 07 января 2019

Хорошо, решил эту проблему, создав параллельный массив, заполненный цветами, и таким образом мы можем вернуться назад во времени с правильными цветами.

...