React
React STEP 16 - State - 2
IT의 큰손
2025. 2. 10. 15:03
728x90
⭐ State
- state를 활용한, 1초에 하나씩 수가 증가되는 프로그램
1. 단계 1
- 구조 생성
class AutoCounter extends React.Component {
render() {
let titleStyle = {
margin: 0,
padding: 0,
fontWeight: "bold",
color: "#333"
};
return (
<p style={titleStyle}>ReactExample</p>
)
}
}
class AuthoCounterBox extends React.Component {
render() {
let boxStyle = {
display: "inline-block",
padding: 20,
backgroundColor: "#eaeaea",
borderRadius: 6
};
return (
<div style={boxStyle}>
<AutoCounter></AutoCounter>
</div>
)
}
}
root.render(
<AuthoCounterBox></AuthoCounterBox>
)
2. 단계 2
- constructor() 함수는 화면이 그려지기 전, 실행되는 함수로서 초기의 데이터를 설정할 수 있습니다.
- componentDidMount() 함수는 화면이 그려진 후, 실행되는 함수입니다.
- setState() 함수는 state 값을 갱신할 때 사용하는 함수입니다.
class AutoCounter2 extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 0
}
}
/*
timer(){
// console.log(this.state.count);
this.setState({
count: this.state.count+10
});
}
componentDidMount(){
// this.timer();
setTimeout(this.timer, 1000);
}
*/
/*
timer(){
this.setState({
count: this.state.count+10
});
}
componentDidMount(){
setTimeout(this.timer.bind(this), 1000);
}
*/
timer=() => {
this.setState({
count: this.state.count+10
});
}
componentDidMount(){
// setTimeout(this.timer, 1000);
setInterval(this.timer, 1000);
}
/*
timer(){
this.setState({
count: this.state.count+10
});
}
componentDidMount(){
setInterval(this.timer.bind(this), 1000);
}
*/
render(){
let titleStyle={
margin: 0,
padding: 0,
fontWeight: "bold",
color: "#333"
};
return(
<p style={titleStyle}>{this.state.count}</p>
);
}
}
class AutoCounterBox2 extends React.Component {
render(){
let boxStyle={
display: "inline-block",
padding: 20,
backgroundColor: "#eaeaea",
borderRadius: 6
};
return(
<div style={boxStyle}>
<AutoCounter2 />
</div>
);
}
}
root.render (
<AutoCounterBox2></AutoCounterBox2>
)
728x90