Hello,

kok nae-ga ha-myun an-dweneun MAGIC...🧚

웹 프로그래밍/공부일지

[Node.js / React.js ] 나 했다 도전! 리엑트 튜토리얼

✿도담도담 2020. 5. 20. 18:15

웹팩 해야하는데 또 새로운거 하고싶어서 리액트 찾다가

튜토리얼만 해봐야지 하고 시작한 리액트 튜토리얼 도전기🤤

틱택토를 만들어 본다구 한다 :)

 

 

https://reactjs-kr.firebaseapp.com/tutorial/tutorial.html

 

Tutorial: Intro to React – React

A JavaScript library for building user interfaces

reactjs.org


react를 전역설치 하고 my-app이라는 react app을 하나 생성해 주었다.

npm install -g create-react-app
create-react-app my-app

해당 명령어를 실행하면 src폴더가 하나 생겼을 텐데

src하위 파일들을 모두 삭제한 후,

/src/index.css와 /src/index.js를 각각 생성해주자.

생성했다면 /src/index.js 에 불러올 파일들을 설정해주자.

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

 

그리고 나서 react를 실행해 보라구 한다.

npm start

해당 명령어를 실행했더니 http://localhost:3000/으로 창이 하나 열렸다!

3000번 포트를 통해 나의 react app을 볼 수 있나보다.

 

아마 node에서 실행 위치를 설정하지 않는한 기본 경로가

/src/index.js라 해당 파일이 자동으로 생성된게 아닌가 한다.

실제로 /src/index.js 파일을 삭제하면 해당 파일이 없다는 경고가 나온다!


이제 React의 기본문법을 터득하며 진짜 틱택토를 맹글어보자.

처음에는 React.Component 클래스를 상속 받아 틱택토의 뼈대( =html )을 만들어놨다.

(틱택토 링크의 index.js를 참조하면된다.)

그리고 ReactDom.render을 통해 화면에 뿌려주고 있다.

JavaScript를 하신 분들이라면 사실 그리 어렵지 않게 분석이 된다. 문법일뿐일테니..!

class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {this.props.value} // value값 추가 (*추가)
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={i}/>; // value값 전달 (*추가)
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</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>
    );
  }
}

class Game extends React.Component {
  render() { // React.Component클래스 사용시 필수 메서드
    return ( // 해당 태그 반환
      <div className="game">
        <div className="game-board">
          <Board /> // Board라는 React.Component 불러오기
        </div>
        <div className="game-info">
          <div>{/* status */}</div> // React에서 {}안의 내용을 해석하는 듯 하다. 따라서 해당 주석은 실제 HTML에서 보여지지 않음
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

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

 

틱택토에서 index.css까지 참고하여 넣어주면 아래와 같은 사진결과물까지 완성했다 :)


여기까지 단순히 나타내는것 까지 했다면 우린 이벤트를 추가할 수 있어야한다!

나는 클릭시 O, X가 나타나도록 하고싶다🤔

 

단계1. 이벤트를 추가해봤다.

 <button className="square" onClick={() => alert('click')}>

단계2. 상태를 저장해봤다.

class Square extends React.Component {
  constructor(props) { // 해당 컴포넌트가 마운트되기 전에 호출
    super(props); // super()로 정의 해주지 않으면 this.props가 생성자 내에서 정의되지 않아 오류
    this.state = {
      value: null,
    };
  }

  render() {
    return (
      <button className="square" onClick={() => this.setState({value: 'X'})}>
        {this.state.value}
      </button>
    );
  }
}

단계3. O, X 번갈아가면서 표시하기!

나중에 승자를 알기 위해선 모든 값을

가지고 있어야 하기에 배열을 하나 만들어주기로 했다.

function Square(props) { // 함수형으로 변형
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
		  squares: Array(9).fill(null),
		  xIsNext: true,
		};
	}
	
	// button 클릭시 실행됨
	handleClick(i) {
		const squares = this.state.squares.slice();
		squares[i] = this.state.xIsNext ? 'X' : 'O';
		this.setState({
			squares: squares,
			xIsNext: !this.state.xIsNext,
		});
	  }
  
	renderSquare(i) {
		return <Square 
			value={this.state.squares[i]}
			onClick={() => this.handleClick(i)}/>;
	}

	render() {
		...생략
	}
}

 

오늘은 여기까지 ;D

아직 손에 안익어서 힘들다...:_(

보면 이해는 가는데 안보고 만들라면 힘들것 같다!