티스토리 뷰

구구단 만들기

<html>

<head>
  <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
  <meta charset="UTF-8">
  <title>구구단</title>
  <div id="root"></div>

  <script type="text/babel">
    class GuGuDan extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          first: Math.ceil(Math.random()*9),
          second: Math.ceil(Math.random()*9), // 임의의 아무 숫자나 만들기
          value:'',
          result:'' // 처음 값은 아무 것도 없기 때문에 빈 값
        }
      }
      render() {
        return (
          <div>
            <div>{this.state.first}곱하기{this.state.second}은?</div>
            <form>
            <input type="number" value={this.state.value} onChange={(e)=>this.setState({value: e.target.value})}/>
            // setState로 설정해줘야 입력 가능
            <button>입력</button>
            </form>
            <div>{this.state.result}</div>
          </div>
        );
      }
    }
  </script>

  <script type="text/babel">
    ReactDOM.render(<GuGuDan />, document.querySelector('#root'));
  </script>
</body>

</html>

수동으로 바꿀 값들만 setState로 설정

 

<html>

<head>
  <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
  <meta charset="UTF-8">
  <title>구구단</title>
  <div id="root"></div>

  <script type="text/babel">
    class GuGuDan extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          first: Math.ceil(Math.random() * 9),
          second: Math.ceil(Math.random() * 9), // 임의의 아무 숫자나 만들기
          value: '',
          result: '' // 처음 값은 아무 것도 없기 때문에 빈 값
        }
      }

      render() {
        return (
          <div>
            <div>{this.state.first}곱하기{this.state.second}은?</div>
            <form onSubmit={(e) => {
              e.preventDefault();
              if (parseInt(this.state.value) === this.state.first * this.state.second) {
                this.setState({
                  result: '정답',
                  first: Math.ceil(Math.random() * 9), // 다음 문제를 위한 숫자 변경
                  second: Math.ceil(Math.random() * 9),
                  value: '' // 값도 초기화
                });
              } else {
                this.setState({
                  result: '땡',
                  value: '' // 값만 초기화
                });
              }
            }}>
              <input type="number" value={this.state.value} onChange={(e) => this.setState({ value: e.target.value })} />
              <button>입력</button>
            </form>
            <div>{this.state.result}</div>
          </div>
        );
      }
    }
  </script>

  <script type="text/babel">
    ReactDOM.render(<GuGuDan />, document.querySelector('#root'));
  </script>
</body>

</html>

위처럼 JSX와 Javascript를 섞어서 쓰면 안됨

아래처럼 따로 클래스의 메소드로 만들어서 써야함

<html>

<head>
  <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
  <meta charset="UTF-8">
  <title>구구단</title>
  <div id="root"></div>

  <script type="text/babel">
    class GuGuDan extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          first: Math.ceil(Math.random() * 9),
          second: Math.ceil(Math.random() * 9),
          value: '',
          result: ''
        }
      }

      onSubmit = (e) => {
              e.preventDefault();
              if (parseInt(this.state.value) === this.state.first * this.state.second) {
                this.setState({
                  result: '정답',
                  first: Math.ceil(Math.random() * 9),
                  second: Math.ceil(Math.random() * 9),
                  value: ''
                });
              } else {
                this.setState({
                  result: '땡',
                  value: '' 
                });
              }
            }

      onChange = (e) => {
        this.setState({ value: e.target.value })
      };

      render() {
        return (
          <div>
            <div>{this.state.first}곱하기{this.state.second}은?</div>
            <form onSubmit={this.onSubmit}>
              <input type="number" value={this.state.value} onChange={this.onChange} />
              <button>입력</button>
            </form>
            <div>{this.state.result}</div>
          </div>
        );
      }
    }
  </script>

  <script type="text/babel">
    ReactDOM.render(<GuGuDan />, document.querySelector('#root'));
  </script>
</body>

</html>

 

구구단 컴포넌트를 여러개쓰면 각 컴포넌트마다 다른 state값을 가짐

> 문제를 다르게 풀 수 있음

 

+숙제

정답 옆에 답도 같이 출력하기

함수에 result를 저렇게 변경했다!

      onSubmit = (e) => {
              e.preventDefault();
              if (parseInt(this.state.value) === this.state.first * this.state.second) {
                this.setState({
                  result: `정답 ! ${this.state.value}`,
                  first: Math.ceil(Math.random() * 9),
                  second: Math.ceil(Math.random() * 9),
                  value: ''
                });
              } else {
                this.setState({
                  result: '땡',
                  value: '' 
                });
              }
            }

선생님 풀이

onSubmit = (e) => {
              e.preventDefault();
              if (parseInt(this.state.value) === this.state.first * this.state.second) {
                this.setState({
                  result: '정답 !' + this.state.value,
                  first: Math.ceil(Math.random() * 9),
                  second: Math.ceil(Math.random() * 9),
                  value: ''
                });
              } else {
                this.setState({
                  result: '땡',
                  value: '' 
                });
              }
            }
728x90

'유튜브 강의' 카테고리의 다른 글

제로초 리액트 강의 2.1 React Hooks  (0) 2021.10.31
제로초 리액트 강의 1.3  (0) 2021.10.31
제로초 리액트 강의 1.1  (0) 2021.10.30
생활코딩 React 1  (0) 2021.10.17
생활코딩 자바스크립트  (0) 2021.10.08
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함