
생성자를 왜 사용해야하고 화살표함수와 기존 함수는 무엇이 다른지 왜 바인딩을 해야하는지에 대해
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hello, World!' };
}
}
위코드에선 constructor 즉 생성자를 통해서 props 값을 가져오고 state에 값을 할당하여
초기값을 지정한다 생성자는 즉 초기값을 지정한다고 보면된다
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hello, World!' };
//추가된 항목
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// 이 메소드가 호출될 때 `this`는 MyComponent 인스턴스를 참조
alert(this.state.message);
}
render() {
// `this.handleClick`은 MyComponent 인스턴스에 바인딩되어 있으므로
// `onClick` 이벤트에 제대로 된 `this` 참조를 가지고 호출됩니다.
return <button onClick={this.handleClick}>Click Me</button>;
}
}
바인딩이 필요한 이유 다음과 같이 랜더링 과정에서 handleClick을 사용한다
하지만 바인딩을 하지 않으면 undefined 또는 다른 컨텍스를 참조하게 된다
생성 초기값을 constructor 초기값에 바인딩 해줘야 handleClick()을 참조하여 정상적으로 함수를 사용할 수 있다
class MyComponent extends React.Component {
state = { message: 'Hello, World!' };
// 화살표 함수를 사용하여 handleClick을 자동으로 바인딩
handleClick = () => {
alert(this.state.message);
};
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
다음과 같이 ArrowFunction 즉 화살표 함수를 사용하게되면 생성자를 따로 생성하지 않아도 자동으로 바인딩되어 사용할 수 있게된다
요즘 React 코드에선 생성자를 찾기 어렵다 이유는 useState와 같은 초기값을 지정해주는 Hook이 존재하기 때문이다
const [count, setCount] = useState('10');
constructor(props) {
super(props);
this.state = { count: '10' };
}