class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello</h1>
<h2>It is {this.state.date.toLocalTimeString()}</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
State는 클래스 컴포넌트에서 사용이 가능하다.(함수형 컴포넌트는 Hooks를 사용)State를 사용하기 위해서는 초기 this.state를 지정하는 class constructor가 필요하다.Clock은 Component를 상속받기 때문에 super키워드를 이용하여 부모 클래스를 상속받고, 클래스 컴포넌트는 항상 props로 기본 constructor를 호출해야 한다.this.state 지정가능한 유일한 공간은 constructor이다.// wrong
this.state.comment = 'Hello';
// correct
this.setState({comment: 'Hello'});
setState() 호출은 단일 업데이트로 한꺼번에 처리가 가능하기 때문에 this.state와 this.props가 비동기적으로 업데이트 될 수 있다.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment
});
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.counter
}));
setState 함수를 호출할 때 리액트는 제공한 객체를 현재 state로 병합한다.
state를 자식 컴포넌트에 props로 전달 할 수 있다.하향식(top-down) 또는 단방향식 데이터흐름class는 객체를 생성하기 위한 템플릿이다.
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
//unNamed
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width'
}
}
//Named
let Rectalgle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
class body는 중괄호 {}로 묶여 있는 안쪽 부분이다.
constructor메서드는 class로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드로 클래스 안에 한 개만 존재할 수 있으며, 여러 개의 constructor 메서드가 존재할 시 SyntaxError가 발생한다.constructor는 부모 클래스의 constructor를 호출하기 위해 super 키워드를 사용한다.