React TicTacToe 앱 만들기(클래스 컴포넌트)

Changmok LEE·2025년 2월 25일

App 컴포넌트 UI 만들기(App.js)

import Board from "./components/Board";
import "./App.css";

function App() {
  return (
    <div className="game">
      <div className="game-board">
        <Board />
      </div>
      <div className="game-info"></div>
      game-info
    </div>
  );
}
export default App;

Board 컴포넌트 생성하기(Board.js)

import React, { Component } from 'react'
import Square from './Square'
import "./Board.css";
export default class Board extends Component {
    constructor(props) {
        super(props);
        this.state = {
            squares: Array(9).fill(null),
        }
    }
    handleClick(i) {
        const squares = this.state.squares.slice();
        squares[i] = i;
        this.setState({ squares: squares });
    }
    renderSquare(i) {
        return <Square
            value={this.state.squares[i]}
            onClick={() => this.handleClick(i)}
        />;
    }
    render() {
        return (
            <div>
                <div className="status">Next Player: X</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>
        )
    }
}

Square 컴포넌트 생성하기(Square.js)

import React, { Component } from 'react'
import "./Square.css";
export default class Square extends Component {

    render() {
        return (
            <button 
            className="square"
                onClick={() => this.props.onClick()}
            >
                {this.props.value}
            </button>
        )
    }
}
profile
이창목

0개의 댓글