React state의 사용 2
포스트
취소

React state의 사용 2

state 사용하기


1초에 하나씩 수가 증가되는 프로그램을 제작하자.

1단계:

1
<div id="root"></div>
1
2
3
#root {
  padding: 10px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class AutoCounter extends React.Component {
  render() {
    let titleStyle = {
      margin: 0,
      padding: 0,
      fontWeight: "bold",
      color: "#333"
    };

    return <p style={titleStyle}>React Example</p>;
  }
}

class AutoCounterBox extends React.Component {
  render() {
    let boxStyle = {
      display: "inline-block",
      padding: 20,
      backgroundColor: "#eaeaea",
      borderRadius: 6
    };

    return (
      <div style={boxStyle}>
        <AutoCounter />
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(<AutoCounterBox />);

2단계:

constructor() 함수는 화면이 그려지기 전, 실행되는 함수로서 초기의 데이터를 설정할 수 있다.

componentDidMount() 함수는 화면이 그려진 후, 실행되는 함수이다.

setState() 함수는 state 값을 갱신할 때 사용되는 함수이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class AutoCounter 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, 1000);
  }

  render() {
    let titleStyle = {
      margin: 0,
      padding: 0,
      fontWeight: "bold",
      color: "#333"
    };

    return <p style={titleStyle}>{this.state.count}</p>;
  }
}

class AutoCounterBox extends React.Component {
  render() {
    let boxStyle = {
      display: "inline-block",
      padding: 20,
      backgroundColor: "#eaeaea",
      borderRadius: 6
    };

    return (
      <div style={boxStyle}>
        <AutoCounter />
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(<AutoCounterBox />);
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.