5. State와 생명주기
함수에서 클래스로 변환
function Clock(props) {
return <div>{props.date.toLocaleTimeString()}</div>;
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}
class Clock extends React.Component {
render() {
return <div>{this.props.date.toLocaleTimeString()}</div>;
}
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}
클래스에 로컬 State 추가하기
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return <div>Hello, {this.state.date.toLocaleTimeString()}!</div>;
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
생명주기 메서드
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timer = setInterval(() => this.tick(),1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({date: new Date()});
}
render() {
return <div>Hello, {this.state.date.toLocaleTimeString()}!</div>;
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
State를 올바르게 사용하기
데이터는 아래로 흐릅니다
- 컴포넌트는 자신의 state를 자식 컴포넌트에 props로 전달할 수 있습니다.
- 모든 state는 항상 특정한 컴포넌트가 소유하고 있으며 그 state로부터 파생된 UI 또는 데이터는 오직 트리구조에서 자신의 “아래”에 있는 컴포넌트에만 영향을 미칩니다.
6. 이벤트 처리하기
- React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용합니다.
- JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달합니다.
<button onClick={activateLasers}>
Activate Lasers
</button>