// function 컴포넌트
function Component() {
return (
<div>
<button
onClick={() => {
console.log("클릭됨");
}}
>
클릭
</button>
</div>
);
}

class Component extends React.Component {
state = {
count: 0
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button
onClick={() => {
this.setState((state) => ({
...state,
count: state.count + 1
}));
}}
>
클릭
</button>
</div>
);
}
}
ReactDOM.render(<Component />, rootEl);

class Component extends React.Component {
state = {
count: 0
};
// this bind 해주기
// 1.
// constructor(props) {
// super(props);
// this.click = this.click.bind(this);
// }
// 2. 기존의 click() 를 에로우 function으로 수정한다.
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.click}>클릭</button>
</div>
);
}
// click() {
// console.log("클릭됨");
// this.setState((state) => ({
// ...state,
// count: state.count + 1
// }));
// }
click = () => {
console.log("클릭됨");
this.setState((state) => ({
...state,
count: state.count + 1
}));
};
// bind 에러 생김
}
ReactDOM.render(<Component />, rootEl);

위에 코드를 보면 먼저 click()를 만들어 메소드를 분리해준다.
그리고 실행하면 this가 바인딩 되지 않았다는 error가 생긴다.
그럼 constructor()부분을 해주던가
아니면 click()을 arrow function으로 변경해주면 된다.