state - input state

tapata·2022년 4월 20일
0

Controlled Component

  • 데이터를 React Component에서 명시적으로 관리
  • input, textarea, select 등의 HTML요소는 기본적으로 자체적인 state를 가지지만 React Component에서 완전히 통제
import { useCallback, useState } from "react";

export default function InputSample(){
  
  const [inputs, setInputs] = useState({
    name:'',
    nickname:''
  });
  
  const {name, nickname} = inputs


  const onChange = useCallback((e:React.ChangeEvent<HTMLInputElement>)=>{    

    const {name, value} = e.target

    setInputs(prev=>({
      ...prev,
      [name]:value 
    }))
  },[])
  
  return (
    <form>
      <input placeholder="이름"  name="name" value={name} onChange={onChange}/>
      <input placeholder="닉네임" name="nickname" value={nickname} onChange={onChange}/>
      <div>
        <b>: </b>
        {name} - {nickname}
      </div>
    </form>
  )
}

Uncontrolled Component

  • DOM요소의 자체적인 state 관리 기능을 사용하고 필요할때 값을 참조만하는 방식
import { useCallback, useRef } from "react";

export default function UnControlledInput(){
  
  //React.LegacyRef<HTMLInputElement>
  const nameInput = useRef<HTMLInputElement>(null);
  const nicknameInput = useRef<HTMLInputElement>(null);

  const onClick = useCallback((e:React.MouseEvent<HTMLButtonElement>)=>{
    e.preventDefault()
    const name = nameInput.current?.value
    const nickname = nicknameInput.current?.value

    console.log(name)
    console.log(nickname)
  },[])
  return (
    <form>
      <input         
        ref={nameInput}        
        />
      <input         
        ref={nicknameInput}/>
      <div>
        <b>: </b>
      </div>
      <button onClick={onClick}>button</button>
    </form>
  )
}

handler 를 각 input에 적용하는 방식

  • 각 input의 onChange props로 전달
import React, { useState } from 'react';

function MyForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    age: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
        />
      </div>
      <div>
        <label>Email:</label>
        <input
          type="email"
          name="email"
          value={formData.email}
          onChange={handleChange}
        />
      </div>
      <div>
        <label>Age:</label>
        <input
          type="number"
          name="age"
          value={formData.age}
          onChange={handleChange}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;

form으로 입력 관리

  • form의 onInput props에 전달
import React, { useState } from 'react';

function MyForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    age: ''
  });

  const handleInput = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onInput={handleInput} onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input
          type="text"
          name="name"
          value={formData.name}
        />
      </div>
      <div>
        <label>Email:</label>
        <input
          type="email"
          name="email"
          value={formData.email}
        />
      </div>
      <div>
        <label>Age:</label>
        <input
          type="number"
          name="age"
          value={formData.age}
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
profile
hello

0개의 댓글

관련 채용 정보