IT_susu

[번역] Tutorial: Completing the Game 2 본문

[ javascript ]/react

[번역] Tutorial: Completing the Game 2

고베베 2019. 4. 17. 19:02

We will now use the prop passing mechanism again. We will modify the Board to instruct each individual Square about its current value ('X', 'O', or null). We have already defined the squares array in the Board’s constructor, and we will modify the Board’s renderSquaremethod to read from it:

renderSquare(i) { return <Square value={this.state.squares[i]} />; }

우리는 전달하는 메커니즘인 prop을 한번 더 사용할 것이다. 우리는 Board를 수정할 것이다. 각각의 square에게 현재 value값을 지시하는 방식으로. (X, O, null) 우리는 이미 squares 배열을 정의했다. Boards의 생성자함수에, 그리고 우리는 boards의 renderSquare 메소드를 수정하고 읽을 것입니다.

 

View the full code at this point

 

Tic Tac Toe

...

codepen.io

Each Square will now receive a value prop that will either be 'X', 'O', or null for empty squares.

각각의 square들은 이제 x, o 혹은 null값을 빈 squares에 value prop을 받을 것이다.

 

Next, we need to change what happens when a Square is clicked. The Board component now maintains which squares are filled. We need to create a way for the Square to update the Board’s state. Since state is considered to be private to a component that defines it, we cannot update the Board’s state directly from Square.

다음, 우리는 square가 클릭됐을 때 발생하는 일을 변경해야한다.  이제 board 컴포넌트는 squares가 채워진 채로 유지한다. 우리는 square가 board의 state를 업데이트 하는 방법을 만들어야 한다. state는 정의된 컴포넌트의 폐쇄적인 것으로 간주되므로, 우리는 board의 state를 square에서 직접적으로 업데이트 할 수없다.

 

Instead, we’ll pass down a function from the Board to the Square, and we’ll have Square call that function when a square is clicked. We’ll change the renderSquare method in Board to:

대신에, 우리는 board에서 square로 함수를 보낼 수 있다. square는 클릭될 때 함수를 호출한다. 우리는 renderSquare 메소드를 바꿀 것이다. 아래와 같이.

Note

We split the returned element into multiple lines for readability, and added parentheses so that JavaScript doesn’t insert a semicolon after return and break our code.

우리는 반환된 엘리먼트를 가독성을 높이기 위해 여러 줄로 나눈다. 그리고 괄호를 추가하여 반환 후 세미콜론을 삽입하지 않고 코드를 마쳤다.

Now we’re passing down two props from Board to Square: value and onClick. The onClickprop is a function that Square can call when clicked. We’ll make the following changes to Square:

Board에서 Square로 두 개의 props를 전달했다: value와 onClick. onClick prop은 함수다. square가 클릭되었을 때 호출할 수 있는 함수다. square에 다음과 같이 변경해보자.

  • Replace this.state.value with this.props.value in Square’s render method
  • Replace this.setState() with this.props.onClick() in Square’s render method
  • Delete the constructor from Square because Square no longer keeps track of the game’s state

this.state.value를 this.props.value로 square의 render 메소드에 바꿔보자.

this.setState()를 this.props.onClick()으로 바꾸자.

square의 생성자 함수를 지우자. 왜냐하면 square는 더 이상 게임의 state를 추적할 필요가 없기 때문이다.

 

After these changes, the Square component looks like this:

이것들을 바꾼 다음 square 컴포넌트는 아래와 같이 생겼다.

When a Square is clicked, the onClick function provided by the Board is called. Here’s a review of how this is achieved:

square가 클릭되었을 때, board가 제공하는 onClick함수가 호출된다. 이것이 어떻게 달성되는지 검토해보자.

 

  1. The onClick prop on the built-in DOM <button> component tells React to set up a click event listener.
  2. When the button is clicked, React will call the onClick event handler that is defined in Square’s render() method.
  3. This event handler calls this.props.onClick(). The Square’s onClick prop was specified by the Board.
  4. Since the Board passed onClick={() => this.handleClick(i)} to Square, the Square calls this.handleClick(i) when clicked.
  5. We have not defined the handleClick() method yet, so our code crashes. If you click a square now, you should see a red error screen saying something like “this.handleClick is not a function”.

1. 내장 DOM 버튼 컴포넌트에 있는 onClick 속성은 리액트에게 event lisntener를 설정하라고 지시한다.

2. 버튼을 클릭하면, 리액트는 square의 render 메소드에 정의된 onClick 이벤트 핸들러를 호출한다.

3. 이 이벤트 핸들러는 this.props.onClick()을 호출한다. square의 onClick 속성은 board에 의해 구체화된다.

4. board가 onclick속성을 square에게 보낸 이후로 square는 클릭될때마다 this.handleClick(i)를 호출한다.

5. 우리는 아직 handleClick 메소드를 정의하지 않았으므로, 우리의 코드는 충돌이 난다. 만약 너가 지금 square를 클릭한다면 빨간색 경고 화면을 보게 될 것이다. this.handleClcik is not a function과 같은 문구화 함께.

 

Note

The DOM <button> element’s onClick attribute has a special meaning to React because it is a built-in component. For custom components like Square, the naming is up to you. We could give any name to the Square’s onClick prop or Board’s handleClick method, and the code would work the same. In React, it’s conventional to use on[Event] names for props which represent events and handle[Event] for the methods which handle the events.

DOM 버튼 요소의 onClick 속성은 react에서 특정한 의미를 지닌다. 왜냐하면 내장 컴포넌트이기 때문이다. square같이 사용자정의 컴포넌트의 이름은 너에게 달렸다. 우리는 어떤 이름이든 줄 수 있다. square의 onClick 속성 또는 board의 handleClick메소드에게. 그래도 코드는 동일하게 동작한다. 리액트에서, 이벤트를 나타내는 속성으로  on[Event]의 이름으로 사용하는 것과 이벤트를 다루기 위한 메소드에게 handle[Event]라는 이름을 사용하는 것은 일반적이다.

When we try to click a Square, we should get an error because we haven’t defined handleClick yet. We’ll now add handleClick to the Board class:

square를 클릭할 때, 에러가 났다. 왜냐하면 handleClick을 아직 정의하지 않았기 때문이다. board 클래스에 handleClick을 추가해보자.

View the full code at this point

After these changes, we’re again able to click on the Squares to fill them, the same as we had before. However, now the state is stored in the Board component instead of the individual Square components. When the Board’s state changes, the Square components re-render automatically. Keeping the state of all squares in the Board component will allow it to determine the winner in the future.

바꾸고 나면, 다시 squares를 클릭하면  이전과 같은 그것들이 채워질 수 있다. 그러나 이제 state는 board 컴포넌트에 저장되어 있다. 각각의 square 컴포넌트 대신에. board의 state를 바꾸면, square 컴포넌트는 자동적으로 다시 렌더한다. board 컴포넌트에서 모든 square들의 상태를 유지하는 것은 미래에 우승자를 결정할 수 있다.

 

Since the Square components no longer maintain state, the Square components receive values from the Board component and inform the Board component when they’re clicked. In React terms, the Square components are now controlled components. The Board has full control over them.

square 컴포넌트에서 더 이상 state를 유지하지 않으므로, square 컴포넌트는 board 컴포넌트로부터 값들을 받고, board 컴포넌트에게 그들이 클릭되었을 때 알린다. 리액트 용어로, square 컴포넌트는 제어된 컴포넌트이다. board는 그것들 모두를 조종한다.

 

Note how in handleClick, we call .slice() to create a copy of the squares array to modify instead of modifying the existing array. We will explain why we create a copy of the squaresarray in the next section.

handleClick이 어떻게 동작하는지에 주목하라. .slice()를 호출하여 squares 배열을 복사한다. 존재하는 배열을 수정하는 것 대신에 수정하기 위해서. 다음 단계에서 왜 우리가 squares 배열을 복사했는지 설명할 수 있다.

Comments