반응형

*리엑트 연습(ox)

- 클릭 시 'X' 체크 및 색상 변경

// HTML
<!-- 리액트 16 버전, 개발에 특화된 버전, 불러오기 -->
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<!-- 리액트 DOM 16 버전, 개발에 특화된 버전, 불러오기 -->
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<h1>게임루트</h1>
<div id="game-root"></div>
// CSS
body,
ul,
li,
h1,
h2,
h3,
h4,
h5,
h6 {
  list-style: none;
  padding: 0;
  margin: 0;
}

/* 커스텀 */
#game-root {
  border: 10px solid black;
  padding: 10px;
}

#game-root > .game {
  border: 10px solid red;
  padding: 10px;
  display: flex;
  flex-direction: column; /* 게임 안의 자식요소들을 세로로 배열 */
}

#game-root > .game > .board {
  padding: 10px;
  border: 10px solid gold;
  display: flex;
  flex-direction: column;
}

#game-root > .game > .board > .square-list {
  display: flex;
  flex-wrap: wrap;
}

#game-root > .game > .board > .square-list > .square {
  border: 10px solid green;
  flex-basis: 33.3333%; /* flex item(flex 요소의 자식)은 축너비를 지정할 때 width, height 보다는, flex-basis를 쓰는게 좋다. */
  box-sizing: border-box; /* border가 축너비 안쪽에 생기게한다. */
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
}

#game-root > .game > .board > .square-list > .square.active {
  background-color: red;
}
// JS
class Square extends React.Component {
  // 생성자
  constructor(props) {
    super(props);

    /* 상태정보를 다루는 변수 */
    this.state = {
      value: null
    };
  }

  getClassName() {
    return "square" + (this.isMarked() ? " active" : "");
  }

  isMarked() {
    return this.state.value != null;
  }

  onClick() {
    const newValue = this.isMarked() ? null : "X";
    var id = this.props.id;
    this.props.onClick(id, newValue);
    this.setState({ value: newValue });
  }

  render() {
    return (
      <div onClick={() => this.onClick()} className={this.getClassName()}>
        {this.state.value}
      </div>
    );
  }
}

class Board extends React.Component {
  constructor(props) {
    super(props);
  }

  renderSquare(id) {
    return <Square key={id} id={id} onClick={this.props.onClickSqure}></Square>;
  }

  renderSquares() {
    const squares = [...Array(9).keys()].map((id) => {
      return this.renderSquare(id);
    });

    return squares;
  }

  render() {
    return (
      <div className="board">
        <h3>보드</h3>

        <div className="square-list">{this.renderSquares()}</div>
      </div>
    );
  }
}
class Game extends React.Component {
  constructor(props) {
    super(props);

    this.playerTurnNo = 1;
  }

  onClickSqure(id, value) {
    alert(value);
  }

  render() {
    return (
      <div className="game">
        <h2>게임</h2>
        <Board onClickSqure={this.onClickSqure} />
      </div>
    );
  }
}

ReactDOM.render(<Game />, document.getElementById("game-root"));
반응형

+ Recent posts