constructor ⇒ 컴포넌트의 생성자 메서드
constructor(props) {
super(props);
this.state = {
number: 0
};
}
리액트 컴포넌트에서 props란 부모 컴포넌트에서부터 전달받은 값입니다.
부모 컴포넌트에서 자식 컴포넌트로 전달할 때 사용되며,
props를 통해 전달된 데이터는 this.props을 통해 접근할 수 있습니다
즉, 기본적으로 우리가 constructor를 호출하지 않더라도
리액트자체에서 기본적으로 super(props)를 호출하고 있습니다.
⇒ 그래야 부모에서 자식으로 데이터가 전달되기 때문입니다.
또 다른 예시
import React, { Component } from "react";
class EventPractice extends Component {
state = {
message: "",
};
constructor(props) {
super(props);
this.state = {
number: 0,
};
}
render() {
return <div>...</div>;
}
}
export default EventPractice;
constructor는 class EventPractice
의 인스턴스가 생성될때 기본적으로 호출되는 메서드 입니다.
따라서 constructor 내부에서 선언하는 ‘this’는 EventPractice
를 뜻합니다.
예시2
import React, { Component } from "react";
class EventPractice extends Component {
state = {
message: "",
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(e) {
this.setState({
message: e.target.value,
});
console.log(e.target.value);
}
handleClick() {
alert(this.state.message);
this.setState({
message: "",
});
}
render() {
return <div>...</div>;
}
}
export default EventPractice;
이 경우에 handleChange함수에서 사용되는 this는 handleChange 함수 자신을 가르킵니다.
따라서 state를 사용할 수 없게 되므로,
this.handleChange = this.handleChange.bind(this);
handleChange의 this를 = this(EventPractice)에 handleChange를 bind한다(this로),
따라서 EventPractice에 bind된 handleChange의 this는 EventPractice를 지칭한다.
즉, 코드로 표현하자면
class EventPractice extends Component = {
state = {
message: ""
}
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
}
이렇게 변환한다.
저는 이렇게 이해했습니다.
이처럼 화살표 함수를 사용하여 constructor메서드 없이도 사용할 수 있습니다.
// constructor 메서드를 삭제합니다.
...
state = {
message: "",
};
handleChange = (e) => {
this.setState({
message: e.target.value,
});
console.log(e.target.value);
};
handleClick = () => {
alert(this.state.message);
this.setState({
message: "",
});
};
...
이는 화살표 함수의 ‘this’가 종속된 인스턴스
를 칭하기 때문입니다.