2017-03-29 1 views
2

이 옵션들을 사용할 수 있습니까? 그들은 모두 같은 방식으로 작동합니까? 나는 ES6을 사용하고있다.React에서 bind (this) 사용하기

onChange={this.makeChange.bind(this)} 

onChange={() => this.makeChange()} 

constructor(props) { 
    super(props); 
    this.makeChange = this.makeChange.bind(this); 
} 

답변

3

예, 세 가지 모두 사용할 수 있습니다. 비록 그들이 똑같은 행동을하더라도, 그들은 서로 다른 성능에 영향을 미친다.

constructor에 함수를 바인딩하는 것이 성능상 가장 좋은 옵션입니다. 왜냐하면 구성 요소가 인스턴스화 될 때 만 생성되기 때문입니다. 다른 솔루션의 경우 구성 요소 (다시)가을 렌더링 할 때마다 새로운 함수가 만들어집니다. 이는 하위 요소가 변경 되었기 때문에 자식 구성 요소도 다시 렌더링하게됩니다.

당신은 공식이에 대한 자세한 내용을보실 수 있습니다이 문서 반작용 : 개인적으로 https://facebook.github.io/react/docs/handling-events.html


을, 나는 (당신이 타이프 라이터 또는 Babel plugin를 사용하는 경우이에만 사용할 수 있습니다) 클래스 속성을 사용하여 다음 구문을 선호한다 :

class LoggingButton extends React.Component { 
    // This syntax ensures `this` is bound within handleClick. 
    // Warning: this is *experimental* syntax. 
    handleClick =() => { 
    console.log('this is:', this); 
    } 

    render() { 
    return (
     <button onClick={this.handleClick}> 
     Click me 
     </button> 
    ); 
    } 
} 

이 옵션은 React docs에도 설명되어 있습니다.

+1

또한 [eslint-plugin-react repository] (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules)에서 바인드 사용을 방지하는 몇 가지 예를 찾을 수 있습니다. /jsx-no-bind.md) ** Prot Prot ** 아래 – dschu

관련 문제