티스토리 뷰

반응형

1. 생성자에서 핸들러에 this를 바인딩

class MyComponent extends React.Component {
    constructor() {
        this.state = {
            someState,
        };
        
        this.myMethod = this.myMethod.bind(this); // this 바인딩
    }
    
    myMethod() {
    	this.setState({someState: 'another state'});
    }
    
    render() {
    	return (
            <button onClick={this.myMethod}></button>
        );
    }
}

2. 핸들러 등록과 함께 this를 바인딩

class MyComponent extends React.Component {
    constructor() {
        this.state = {
            someState,
        };
    }
    
    myMethod() {
    	this.setState({someState: 'another state'});
    }
    
    render() {
    	return (
            <button onClick={this.myMethod.bind(this)}></button> {/* this 바인딩 */}
        );
    }
}

3. arrow function 으로 래핑

  * 메서드가 props로 자식 노드에게 전달될 경우, 자식 노드에서 해당 메소드에 대한 렌더링을 다시 진행할 수도 있으므로 권장하지 않는 방법이다.

class MyComponent extends React.Component {
    constructor() {
        this.state = {
            someState,
        };
    }
    
    myMethod() {
    	this.setState({someState: 'another state'});
    }
    
    render() {
    	return (
            <button onClick={() => this.myMethod()}></button> {/* arrow function 래핑 */}
        );
    }
}

4. 퍼블릭 클래스 필드 문법 활용

  * 실험적

class MyComponent extends React.Component {
    constructor() {
        this.state = {
            someState,
        };
    }
    
    // 퍼블릭하게 선언
    myMethod = () => {
    	this.setState({someState: 'another state'});
    }
    
    render() {
    	return (
            <button onClick={this.myMethod}></button>
        );
    }
}
반응형
댓글