[reactチュートリアル]ポインティングシンボルを追加(2/2)


-追加のタッチコントロールを実施する図(1/2)

4.切替ボタンを追加し、昇順または降順に並べて移動します。


5.勝者が決まったら、勝負を決める三角形を強調してください。


どう考えても分からないのでグーグルで解決しましたが….私はまだコードをよく理解していないので、後で説明しましょう.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

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

class Board extends React.Component {
  renderSquare(i) {
    let extraClassName = 'square';
    if (this.props.winnerCells && this.props.winnerCells.indexOf(i) > -1){
      extraClassName = 'square highlighted';
    }
    return (
      <Square
        key={i}
        extraClass={extraClassName}
        value={this.props.squares[i]}
        onClick={() => {this.props.onClick(i);}}
      />
    );
  }

  render() {
    const boardRow=[];
    let k=0;
    for (let i = 0; i<3;i++){
      const square = [];
      for (let j=0;j<3;j++){
        square.push(this.renderSquare(i*3+j));
        k++;
      }
      boardRow.push(<div key={k} className="board-row">{square}</div>)
    }
    return (
      <div>
        {boardRow}
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
          position:{
            x:null,
            y:null,
          }
        }
      ],
      stepNumber: 0,
      xIsNext: true,
      isAscending :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:{
            x:parseInt(i/3)+1,
            y:i % 3 + 1,
          }
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }

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

  handleSortBtn(){ // 정렬 버튼 눌렀을 때 동작
    this.setState({isAscending:!this.state.isAscending});
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winnerInfo = calculateWinner(current.squares);
    const winner = winnerInfo?winnerInfo[0]:winnerInfo;
    const winnerCells = winnerInfo ? winnerInfo.slice(1) : winnerInfo;
    const isAscending = this.state.isAscending;

    const moves = history.map((step, move) => {
      const desc = move ?
        'Go to move #' + move +"("+step.position.x+", "+step.position.y+")":
        'Go to game start';
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)} style={{fontWeight:this.state.stepNumber===move?'bold':null}}>{desc}</button> 
        </li>
      );
    });

    if(!isAscending){
      moves.reverse();
    }
    
    const sortBtnText = isAscending?"내림차순으로":"오름차순으로";
    const sortBtn = (
      <button onClick={()=>this.handleSortBtn()}>
        {sortBtnText}
      </button>
    );

    let status;
    if (winner) {
      status = "Winner: " + winner;
    } else {
      // 6. 무승부 표시
      if(this.state.stepNumber==9){
        status="무승부";
      }else{
        status = "Next player: " + (this.state.xIsNext ? "X" : "O");
      }
    }

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

// ========================================

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

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], a, b, c];
    }
  }
  return null;
}