티스토리 뷰

유튜브 강의

제로초 리액트 강의 1.3

2021bong 2021. 10. 31. 16:49
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>
        );
      }

리액트에서 항상 하나의 태그로 감싸져있어야하는데 그럼 쓸데없는 div태그가 하나 더 생기게 됨

이걸 없애고 싶으면

 

render() {
        return (
          <>
            <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>
          </>
        );
      }

이렇게 빈태그를 생성할 수 있음 하지만 현재 스크립트 태그로 붙여넣은 바벨에서는 지원을 안해서 다른 버전을 깔아야함

 

그래서 그럴 땐 이렇게 쓰면 됨 React.Fragment로 감싸기

render() {
        return (
          <React.Fragment>
            <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>
          </React.Fragment>
        );
      }

우리가 만든 함수를 메소드로 뺐을 때는 무조건 화살표 함수를 사용

> function을 사용하면 this가 달라지기 때문

render에서는 써도 상관없음!


 

constructor를 안쓰고 super(props)없애고 state에서 this 빼서도 사용 가능

class GuGuDan extends React.Component {
        state = {
          first: Math.ceil(Math.random() * 9),
          second: Math.ceil(Math.random() * 9),
          value: '',
          result: ''
        }

예전 state를 이용해서 새 state를 만들 때는 return함수를 사용할 것!

setState가 비동기라서 발생하는 문제를 해결하기위해서 넣는 것임

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

DOM에 접근하기

input태그에 포커스 주기

<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((prevState)=>{
                  return{
                  result: '정답 !' + prevState.value,
                  first: Math.ceil(Math.random() * 9),
                  second: Math.ceil(Math.random() * 9),
                  value: ''
                  }
                });
                this.input.focus(); // document.querySelector('input').focus(); 와  동일
              } else {
                this.setState({
                  result: '땡',
                  value: '' 
                });
                this.input.focus(); // 여기도 추가
              }
            }

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

      input; // 선언

      render() {
        return (
          <div>
            <div>{this.state.first}곱하기{this.state.second}은?</div>
            <form onSubmit={this.onSubmit}>
              <input ref={(c)=>{this.input = c;}} type="number" value={this.state.value} onChange={this.onChange} /> 
              // 이렇게 ref를 넣음, input이름은 마음대로 설정 가능,  이렇게 DOM에 접근 가능
              <button>입력</button>
            </form>
            <div>{this.state.result}</div>
          </div>
        );
      }
    }
  </script>

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

</html>

 

함수는 따로 빼기!

<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((prevState)=>{
                  return{
                  result: '정답 !' + prevState.value,
                  first: Math.ceil(Math.random() * 9),
                  second: Math.ceil(Math.random() * 9),
                  value: ''
                  }
                });
                this.input.focus();
              } else {
                this.setState({
                  result: '땡',
                  value: '' 
                });
                this.input.focus();
              }
            }

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

      input;

      onRefInput = (c)=>{this.input = c;}; // 빼기

      render() {
        return (
          <div>
            <div>{this.state.first}곱하기{this.state.second}은?</div>
            <form onSubmit={this.onSubmit}>
              <input ref={this.onRefInput} type="number" value={this.state.value} onChange={this.onChange} /> 
              // 이렇게 ref를 넣음, input이름은 마음대로 설정 가능,  이렇게 DOM에 접근 가능
              <button>입력</button>
            </form>
            <div>{this.state.result}</div>
          </div>
        );
      }
    }
  </script>

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

</html>

setState를 할 때 마다 render가 실행됨!

>오래 걸리는 작업인데 자꾸 렌더를 돌리면 서비스가 안돌아가겠지요..

나중에 성능최적화 할 때 중요한 개념이니 알고 있을 것!

 

render 안에 안넣고 함수를 따로 빼는 이유

>렌더링 할 때 마다 함수가 계속 생기면 안되겠지요.. 성능이 안좋아질테니...

728x90

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

제로초 리액트 강의 2.2  (0) 2021.11.01
제로초 리액트 강의 2.1 React Hooks  (0) 2021.10.31
제로초 리액트 강의 1.2 구구단 만들기  (0) 2021.10.30
제로초 리액트 강의 1.1  (0) 2021.10.30
생활코딩 React 1  (0) 2021.10.17
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함