뭐든 즐기면서 ;)

React Event 처리 시 주의사항 / React 이벤트 처리 시 주의사항 본문

FRONT/React

React Event 처리 시 주의사항 / React 이벤트 처리 시 주의사항

Tada.*+ 2021. 11. 8. 22:55
728x90

※ 주의사항

* JSX 콜백 안에서 this를 사용할 경우에 주의해야 합니다.

 

1. Bind 사용

- bind를 해주기 전과 후의 차이점

 

아래 코드 중 'this.handleClick = this.handleClick.bind(this);'에 집중해 주세요.

constructor에 작성한 '.bind(this)'를 통하여 'constructor'와 'handleClick' 함수 내에서 this를 확인하였을 때, 같은 객체(Toggle 클래스)를 가리키는 것을 확인할 수 있습니다. (이미지 참고)

 

  • bind처리를 하였을 때
class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {isToggleOn: true};

        // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
        this.handleClick = this.handleClick.bind(this);
        console.log('constructor this', this);
    }

    handleClick() {
        console.log('handleClick this', this);
        this.setState(prevState => ({
            isToggleOn: !prevState.isToggleOn
        }));
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>
        );
    }
}

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

  • bind처리를 하지 않았을 때
constructor(props) {
	super(props);
    this.state = {isToggleOn: true};

    // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
    //this.handleClick = this.handleClick.bind(this);
    console.log('constructor this', this);
}

- bind란? this에 함수를 바인딩시키는 것. 간단히 말하자면, 함수 내에서 쓰일 this를 지정할 수 있습니다.

사전적 의미의 bind = 결속시키다, 묶다

아래와 같이 수정한 후 this 객체 확인하기

this.handleClick = this.handleClick.bind({sample:'HyePark'});

2. 화살표 함수 사용

- 화살표 함수는 상위 스코프의 this를 가리킴.(** 클래스 문법을 사용할 경우에만 가능.)

일반 함수의 경우, 함수를 호출할 때 어떻게 호출되었는지에 따라 this에 바인딩할 객체가 동적으로 결정되어지지만,

화살표 함수의 경우, 함수를 선언할 때 this에 바인딩할 객체가 정적으로 결정됩니다.

handleClick = () => {
		console.log('handleClick this', this);
		this.setState(prevState => ({
		isToggleOn: !prevState.isToggleOn
	}));
}

 

3. 이벤트에서 콜백 화살표 함수 사용

render() {
	// 이 문법은 `this`가 handleClick 내에서 바인딩되도록 합니다.
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }

 

이전 글 : 2021.11.07 - [UI/React] - React Event 처리하기 / React 이벤트 처리하기

 

React Event 처리하기 / React 이벤트 처리하기

※ React에서 Event 처리하는 방법 React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용합니다. JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달합니다. - javascript와 React에서의 함수

tadaiswhatever.tistory.com

다음 글 : 2021.11.09 - [UI/React] - React 조건부 렌더링1 if

 

React 조건부 렌더링1 if

※ 조건부 렌더링 : 조건에 따라 다양한 컴포트 보여주기 - JavaScript와 같이 보여주기가 가능합니다. 1. if문 사용 방법 - 아래 두 개의 컴포넌트가 존재합니다. function UserGreeting(props) { return Welcome..

tadaiswhatever.tistory.com

 

728x90
Comments