React의 폼 관리는 주로 컴포넌트의 상태(state)를 이용하여 사용자 입력을 처리하는 방식으로 되어 있다.
기본적으로 두 가지 방식이 있다: 제어 컴포넌트, 비제어 컴포넌트
제어 컴포넌트 >>
제어 컴포넌트에서는, React 컴포넌트가 폼 데이터를 관리한다.
(폼의 각 입력 필드의 값(value)이 컴포넌트의 상태(state)에 의해 제어된다는 것)
import React, { useState } from 'react';
function Form() {
const [value, setValue] = useState('');
function handleChange(event) {
setValue(event.target.value);
}
function handleSubmit(event) {
alert('입력된 값: ' + value);
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>
이름:
<input type="text" value={value} onChange={handleChange} />
</label>
<button type="submit">제출</button>
</form>
);
}
<input type="text" value={value} onChange={handleChange} />: value 속성은 value 상태를 나타낸다. onChange 이벤트 핸들러로 handleChange 함수를 연결해서 입력 값이 변경될 때마다 handleChange 함수가 호출된다.
비제어 컴포넌트 >>
비제어 컴포넌트에서는 폼 데이터를 DOM 자체가 관리한다.
import React, { useRef } from 'react';
function Form() {
const inputRef = useRef();
function handleSubmit(event) {
alert('입력된 값: ' + inputRef.current.value);
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>
이름:
<input type="text" ref={inputRef} />
</label>
<button type="submit">제출</button>
</form>
);
}
const inputRef = useRef() : useRef를 사용하여 inputRef 라는 ref 객체를 만든다.
이 ref 객체는 입력 필드를 가리키고, 나중에 DOM 요소에 접근할 때 사용된다.
function handleSubmit(event) : handleSubmit 함수는 양식이 제출될 때 호출되는 함수다. inputRef.current.value 를 사용하여 입력 필드의 값을 가져오고, 경고창(alert)으로 표시한다. event.preventDefault() 를 호출해서 기본 동작을 막는다.
(양식이 제출될 때, 브라우저는 일반적으로 페이지를 새로고침하거나 다른 페이지로 이동한다. 그런데 이 코드에서는 submit 이벤트를 handleSubmit으로 처리하고 있다(경고창을 띄우기 위함). 그러므로 event.preventDefault() 를 호출해서 브라우저가 페이지를 새로고침하거나 다른 페이지로 이동하는 것을 막고, 대신에 폼 제출 이벤트를 처리하고 추가적인 동작을 수행할 수 있게 한다.(경고창을 띄울 수 있게 한다))
<form onSubmit={handleSubmit}> : onSubmit 이벤트 핸들러로 handleSubmit 함수를 연결한다. 양식이 제출될 때 handleSubmit 함수가 실행된다.
<input type="text" ref={inputRef} /> : ref 속성을 사용하여 inputRef를 연결한다. 나중에 자바스크립트에서 inputRef.current 를 사용하여 입력 필드에 접근할 수 있다.
'JavaScript > React' 카테고리의 다른 글
Beautiful dnd 드래그 기능 구현 중 오류(Cannot find droppable entry with id [droppable] at handleError)(React + TypeScript) (0) | 2024.03.26 |
---|---|
React Router의 핵심 기능과 사용법 (0) | 2024.03.25 |
React의 리스트 렌더링과 키 관리 (0) | 2024.03.24 |
React 조건부 렌더링: 설명과 예제 (0) | 2024.03.24 |
React의 이벤트 처리 소개 (0) | 2024.03.23 |