2017-05-24 1 views
0

React 튜토리얼에서 그들은 tic-tac-toe 게임을 만든다. 이 코드를 얻을 때까지는 쉽게 이해할 수있었습니다.어디에서 왔는가?

handleClick(i) { 
     const squares = this.state.squares.slice(); 
     squares[i] = 'X'; 
     this.setState({squares : squares}); 
} 

이 코드는 click 이벤트 처리기입니다. 하지만 코드에서이 변수가 어디서 왔는지는 알지 못했습니다. React가 클릭하는 정확한 버튼을 어떻게 알 수 있습니까? 튜토리얼을 읽는 사람이 설명해 주시겠습니까? 원본을 찾을 때까지

import React, {Component} from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App'; 
import './index.css'; 


class Square extends Component { 
    render(){ 
     return (
      <button 
       className="square" 
       onClick={() => this.props.onActivation()}> 
       {this.props.value} 
      </button> 
     ); 
    } 
} 
class Board extends Component { 
    constructor(){ 
     super(); 
     this.state = { 
      squares: Array(9).fill(null), 
     } 
    } 
    handleClick(i) { 
     const squares = this.state.squares.slice(); 
     squares[i] = 'X'; 
     this.setState({squares : squares}); 
    } 
    renderSquare(i) { 
     return (
      <Square 
      value={this.state.squares[i]} 
      onActivation={()=>this.handleClick(i)} 
      /> 
     ); 
    } 
    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> 
      {this.renderSquare(3)} 
      {this.renderSquare(4)} 
      {this.renderSquare(5)} 
      </div> 
      <div> 
      {this.renderSquare(6)} 
      {this.renderSquare(7)} 
      {this.renderSquare(8)} 
      </div> 
      </div> 
      ) 
    } 
} 

class Game extends Component { 
    render() { 
     return (
      <div className="game"> 
      <div className="game-board"> 
      <Board/> 
      </div> 
      <div className="game-info"> 
     <div>{/* status */}</div> 
    <ol>{/* TODO */}</ol> 
    </div> 
    </div> 
    ) 
    } 
} 

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

에서 사용할 수있는 이유

는, 즉'i' 인수입니다입니다 그 방법에 ... – Li357

+0

알아,하지만 값이 handleClick (i)에서 왔어? 클릭 할 때만 실행됩니다. 맞습니까? –

+0

무슨 소리 야? 값이 메서드 – Li357

답변

0

변수와 함수를 따르

여기에 전체 코드가 (I 개인 목적으로 onActivationonClick 소품을 변경) 간다.

squares[i] = 'X';으로 시작하는이 줄은 handleClick()의 내부에 있으며 그 매개 변수는 i입니다. handleClick()onActivation={()=>this.handleClick(i)} 내에서 호출되며 renderSquare() 함수에 있으며이 매개 변수는 다시 i입니다. renderSquare()은 구성 요소의 render() 메소드에서 사용되며, 여기서 renderSquare()의 각 사용에는 숫자 인수가 전달됩니다.

예 : this.renderSquare(7). 이 경우 숫자 7renderSquare에서 handleClick에서 squares[i]으로 전달됩니다. 당신은 내가 '난'renderSquare()의 범위에 빠진 것을 발견 enter image description here

+0

좋아, 알 겠어.하지만 'handleClick (i)'는 내가 버튼을 클릭 할 때만 호출된다. 그래서, 그 'i' 값은 어딘가에 저장됩니까? 값이 저장되는 위치를 볼 수 없습니다. –

+0

예. 'this.handleClick()'은 각'Square' 컴포넌트의'onClick'이라고합니다. 각각의'Square' 컴포넌트는'renderSquare()'함수를 호출함으로써 생성됩니다.이 함수는 인자로 전달 된 값 ('i')를가집니다. –

0

시각적 형식을 경우가 handleCLick()

관련 문제