[React.js] Class Component bind() 좀 편하게 쓰자!
1. 글을 쓰는 이유
리액트를 이용하여 애플리케이션을 만들 때 클래스 컴포넌트를 이용한다면 반드시 함수에 this를 바인딩 해주어야 한다. 바인딩을 안한다면 함수 안에서 쓰여진 this는 undefined를 가리킬 것이다. 하지만 생성자에서 함수 하나하나 바인딩 하는 것이 비효율적이라고 생각이 들어 bind()를 쓰지 않는 방법을 알게 되어서 기록한다.😁
2. 기존 방법
import React, { Component } from 'react';
class Sample extends Component {
constructor(props) {
super(props);
this.state = {
name:'홍길동'
}
this.handleClick = this.handleClick.bind(this);
}
function handleClick() {
alert(this.state.name);
}
render() {
return(
<div>
<button onClick={this.handleClick}>클릭</button>
</div>
)
}
}
생성자 constructor에서 handleClick함수의 바인딩을 해주고 있다.
3. 개선 방법(Arrow Function)
import React, { Component } from 'react';
class Sample extends Component {
constructor(props) {
super(props);
this.state = {
name:'홍길동'
}
}
handleClick = () => {
alert(this.state.name);
}
render() {
return(
<div>
<button onClick={this.handleClick}>클릭</button>
</div>
)
}
}
handleClick함수를 Arrow Function으로 정의하여 bind()를 생략한다.
4. constructor 없애버리기
import React, { Component } from 'react';
class Sample extends Component {
state = {
name : "홍길동",
age : 50
}
handleClick = () => {
alert(this.state.name);
}
render() {
const { gender } = this.props;
const { name, age } = this.state;
return(
<div>
<button onClick={this.handleClick}>클릭</button>
<p>{ name }</p>
<p>{ age }</p>
<p>{ gender }</p>
</div>
)
}
}
props와 state는 구조분해 할당으로, 함수는 Arrow Function으로 한다.
Author And Source
이 문제에 관하여([React.js] Class Component bind() 좀 편하게 쓰자!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@apro_xo/React.js-Class-Component-bind-좀-편하게-쓰자저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)