-
제어 컴포넌트와 비제어 컴포넌트
`제어 컴포넌트`는 React에 의해서 값이 제어 되는 것, `비제어 컴포넌트`는 React에 의해서 값이 제어되지 않는 컴포넌트 이다.
제어 컴포넌트
제어 컴포넌트 같은 경우 input의 변화를 하나하나 다 체크해서 제어한다.
사용자가 작성할 때 마다 모든 것을 제어한다.
ex) onChange value를 주는 방법
비제어 컴포넌트
비제어 컴포넌트는 button type submit 같이,
사용자가 버튼을 눌렀을때 제어하는 방식이다.
제어 컴포넌트와 비제어 컴포넌트의 장, 단점
`제어 컴포넌트`의 장점은 하나하나씩 관리할 수 있다.
하지만 개발자가 코드가 많아진다.
`비제어 컴포넌트` 장점은
하나하나 제어하지않으니까 개발자가 짧은 코드로도 가능하다
단점은 제어컴포넌트의 장점의 반대이다
하나하나에 대해서 제어를 할수가 없다!
그렇다면 하나하나 제어를 언제할까?
ex) 한글로만 쓰고 싶을때,
중간에 사용자가 영어를 입력할 때 한글만 들어갈 수 있습니다. 라고 보여주고 싶을때 제어 컴포넌트를 사용한다
제어 컴포넌트 예시
import { useState } from "react"; const TodoForm = () => { const [title, setTitle] = useState(""); const [content, setContent] = useState(""); const onSubmitHandler = (e) => { e.preventDefault(); setTitle(e.target.value); }; return ( <div> <form onSubmit={onSubmitHandler}> <input type="text" placeholder="제목을 입력해 주세요" value={title} onChange={(e) => setTitle(e.target.value)} /> <input type="text" placeholder="내용을 입력해 주세요." value={content} onChange={(e) => setContent(e.target.value)} /> <button type="submit">등록</button> </form> </div> ); }; export default TodoForm;
기존에 자주 쓰는 방식이다
`e.target.value`로 상태변화를 감지한다.
비제어 컴포넌트 예시
const TodoForm = ({ setTodos }) => { const onSubmit = (e) => { e.preventDefault(); const formData = new FormData(e.target); const title = formData.get("title"); const content = formData.get("content"); if (!title.trim() || !content.trim()) return alert("제목과 내용을 입력해 주세요."); const nextTodo = { id: crypto.randomUUID(), title, content, isDone: false, }; e.target.reset(); setTodos((prevTodos) => [nextTodo, ...prevTodos]); }; return ( <div> <form onSubmit={onSubmit}> <input type="text" placeholder="제목을 입력해 주세요" name="title" /> <input type="text" placeholder="내용을 입력해 주세요." name="content" /> <button type="submit">등록</button> </form> </div> ); }; export default TodoForm;
비제어 컴포넌트에는 `name`만 넣어주면 제어가 가능하다.
`button type`을 `submit`으로 해주고 `onSubmit`이 실행이 된다.
'📚 이론정리 > React & Next.js' 카테고리의 다른 글
✏️ 사용자 경험에 맞춘 skelecton 라이브러리 (0) 2024.06.23 ✏️ 커스텀 훅(Custom Hook)과 유틸함수(util function)의 차이점 (0) 2024.05.19 ✏️ Virtual DOM을 사용하는 이유? (0) 2024.03.13 ✏️ React의 불변성 (0) 2024.03.12 common폴더와 elements폴더의 차이점,layout폴더 (0) 2024.03.09 댓글