so woon!

[React] Inputs, State 본문

ReactJS/개념정리

[React] Inputs, State

xowoony 2023. 3. 11. 13:43

학습일 : 2023. 03. 11


jsx 는 HTML과 비슷하지만 몇가지 기억할 것이 존재한다.

 

class 을 사용하면 안되고, 그 대신 className 을 사용한다.

for 을 사용하면 안되고, 그 대신 htmlFor 을 사용한다.

 

 

 

label 태그에 htmlFor="minutes" 를 주고

그 밑에 있는 input 태그에 id="minutes 를 주면

label 태그 즉 Minutes라는 글자를 클릭했을 경우

밑에 있는 input 태그가 활성화 된다. (커서가 깜빡이게 됨)

 

 

 

  <script type="text/babel">
    function App() {
      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
          <input id="minutes" placeholder="Minutes" type="number" />

          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />
        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

 

 

 

실행결과는 아래와 같다

 

 

 

input 태그의 value는 우리가 통제할 수 없기 때문에
state를 생성하도록 한다.

  <script type="text/babel">
    function App() {
      const [] = React.usestate()
      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
          <input id="minutes" placeholder="Minutes" type="number" />

          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />
        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

위에서 

const [] = React.usestate()


()안에는 default 값을 작성해주도록 한다.

default 값은 없기때문에

아무것도 적지 않거나  0이나 "" 를 적어주도록 한다.

useState 는 array를 제공한다.
그리고 첫 번째 element가 현재의 값이 된다.
두번째 element엔 첫번재 element를 수정해주는 modifier 함수가 들어가게 된다.

 

아래처럼

const [minutes, setMinutes] = React.usestate()

이렇게 작성해주게 되면

input 태그에 value 값을 줄 수 있게 된다.

  <script type="text/babel">
    function App() {
      const [minutes, setMinutes] = React.usestate();
      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
         
          <input
            value={minutes} 
            id="minutes"
            placeholder="Minutes"
            type="number"
          />

          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />
        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

 

다시 정리를 해보자면

  <script type="text/babel">
    function App() {
    
      // state 생성
      const [minutes, setMinutes] = React.usestate();
      
      
      // onChange 함수 생성
      const onChange = () => {
        console.log("somebody wrote!!");
      }


 // value는 minutes 값이다. 이는 위 state인 const [minutes, setMinutes] 에서 minutes이다.
      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
          <input
            value={minutes}
            id="minutes"
            placeholder="Minutes"
            type="number"
            onChange={onChange}
          />

          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />
        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

 

 

-총정리-

 

input 태그에 value를 줄려면

state 생성이 필요하고

state는

const [minutes, setMinutes] = React.userstate();

이런식으로 생성하게 된다. 

minutes 즉, array의 첫번째 item은 value에 해당하며,

setMinutes 즉, array의 두번째 item은 value인 minutes를 수정하고 component를 새로고침할 때 쓰는 함수이다.

 

이렇게 작성해주게 되면

input태그에 부여된 value값과 state의 value가 같아지게 된다.

 

input 변화가 생기면(사용자가 입력하게 되면) onChange 함수를 실행시키게 된다

위에서 작성한 onChange함수가 실행된다. 즉 console.log("somebody wrote");가 실행되게 된다.

 

 

실행결과는 아래와 같다.

 

 

 

 

============================================================================================

 

한가지 더 재밌는거

<script type="text/babel">
    function App() {
      // state 생성
      // array 의 첫번째 item 은 minutes 이며 이는 value 이다.
      // array 의 두번째 item 은 setMinutes 이며 이는 value를 수정하고, component를 새로고침 할 때 쓰는 함수이다.
      const [minutes, setMinutes] = React.useState();
      // onChange 함수 생성
      const onChange = (event) => {
        console.log(event.target.value);
      }


      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
          <input
            value={minutes} // minutes 값이다. 이는 위 const [minutes, setMinutes] 즉 state에 있다.
            id="minutes"
            placeholder="Minutes"
            type="number"
            onChange={onChange}
          />

          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />

        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

 

console.log(event.target.value); 를 찍어보면

개발자 도구 콘솔에

 

 

  // onChange 함수 생성
      const onChange = (event) => {
        console.log(event.target.value);
      }

 

이렇게 입력한 값이 실시간으로 찍히게 됨을 볼 수 있다.

 

 

 

 

그리고 바뀐 데이터 업데이트를 위해 아래와 같이 적어준다.

const onChange = (event) => {
        setMinutes(event.target.value);
      };

 

 <script type="text/babel">
    function App() {
      // state 생성
      // array 의 첫번째 item 은 minutes 이며 이는 value 이다.
      // array 의 두번째 item 은 setMinutes 이며 이는 value를 수정하고, component를 새로고침 할 때 쓰는 함수이다.
      const [minutes, setMinutes] = React.useState();
      // onChange 함수 생성
      const onChange = (event) => {
        setMinutes(event.target.value);
      };


      return (
        <div>
          <h1 classname="hi">Super Converter</h1>

          <label htmlFor="minutes">Minutes</label>
          <input
            value={minutes} // minutes 값이다. 이는 위 const [minutes, setMinutes] 즉 state에 있다.
            id="minutes"
            placeholder="Minutes"
            type="number"
            onChange={onChange}
          />

          <h4>You want to convert {minutes}</h4>
          <label htmlFor="hours">Hours</label>
          <input id="hours" placeholder="Hours" type="number" />

        </div>
      );
    }
    const root = document.getElementById("root");
    ReactDOM.render(<App />, root);
  </script>

 

 

 

업데이트 되는 것을 보기 쉽게 h4 태그를 추가해서 보도록 한다

 

실행결과는 아래와 같다.

 

you want to convert 옆 숫자가 실시간으로 업데이트 됨을 볼 수 있다.

 

 

 

 

 

 

 

 

 

'ReactJS > 개념정리' 카테고리의 다른 글

[React] flip function  (0) 2023.03.11
[React] 시간 변환기 만들기 (분 ->시)  (0) 2023.03.11
[React] State 바꾸기  (0) 2023.03.07
[React] 리렌더링  (0) 2023.03.07
[React] React.useState 사용하기  (0) 2023.03.06
Comments