LoginSignup
0
1

More than 3 years have passed since last update.

Reactの公式チュートリアルを進化させる(2)

Last updated at Posted at 2021-02-27

はじめに

Reactの公式チュートリアルを進化させる(1)の続きです.
React公式から与えられた課題はこれでした.

まだ時間がある場合や、今回身につけた新しいスキルを練習してみたい場合に、あなたが挑戦できる改良のアイデアを以下にリストアップしています。後ろの方ほど難易度が上がります:
1. 履歴内のそれぞれの着手の位置を (col, row) というフォーマットで表示する。
2. 着手履歴のリスト中で現在選択されているアイテムをボールドにする。
3. Board でマス目を並べる部分を、ハードコーディングではなく 2 つのループを使用するように書き換える。
4. 着手履歴のリストを昇順・降順いずれでも並べかえられるよう、トグルボタンを追加する。
5. どちらかが勝利した際に、勝利につながった 3 つのマス目をハイライトする。
6. どちらも勝利しなかった場合、結果が引き分けになったというメッセージを表示する。

今回は課題2に取り組みます.

課題内容

課題2の内容はこちら

  1. 着手履歴のリスト中で現在選択されているアイテムをボールドにする。

実装済みのやり直しボタンのうち,表示されている盤面の状態を表しているものを太字にしろということでしょうか.

つまり,これ↓を
after1.png

こうして↓
after2.png

戻ったりしてもこうなるよ↓
after2-2.png

ということでしょう.

実装

CSSで太字用クラスを用意して,太字にしたいときにそのクラスを割り当てるという方針でいきます.

まずは,index.cssに太字用クラスを追記します.

index.css
/* 太字クラスを追加 */
.bold {
  font-weight: bold;
}

あとは,「現在選択されているアイテム」にだけこれを割り当てれば良いだけです.
stepNumberは現在のターンを表しているので,ボタンのうち上からstepNumber番目を太字にすれば良さそうです.

index.jsを開いて,Gameコンポーネントのrenderメソッドのmovesの部分を以下のように書き換えましょう.

index.js
    const moves = history.map((value, index) => {
      const desc = index ?
        `Go to move #${index} (${(value.position % 3) + 1},${Math.floor(value.position / 3) + 1})`:
        'Go to game start';
      return (
        <li key={index}>
          <button 
             onClick={() => this.jumpTo(index)} 
        className={index === this.state.stepNumber ? 'bold' : ''}> // [追加行] indexとstepNumberが等しいときboldを割り当てる
        {desc}
      </button>
        </li>
      );
    });

実装例

課題2終了時点のコードです.

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// Square関数コンポーネント
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}


// Boardクラスコンポーネント
class Board extends React.Component {
  renderSquare(i) {
    return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
  }

  render() {
    return (
      <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>
    );
  }
}


// Gameクラスコンポーネント
class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        position: null,
      }],
      stepNumber: 0,
      xIsNext: true,
    };
  }

  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.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares,
        position: i,
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0,
    });
  }

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

    const moves = history.map((value, index) => {
      const desc = index ?
        `Go to move #${index} (${(value.position % 3) + 1},${Math.floor(value.position / 3) + 1})`:
        'Go to game start';
      return (
        <li key={index}>
          <button onClick={() => this.jumpTo(index)} className={index == this.state.stepNumber ? 'bold' : ''}>{desc}</button>
        </li>
      );
    });

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

    return (
      <div className="game">
        <div className="game-board">
          <Board squares={current.squares} onClick={(i) => this.handleClick(i)}/>
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}


// calculateWinner関数コンポーネント
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')
);

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1