-
React 기초 - form 태그Framework & Library/React 2021. 9. 22. 18:35
form 태그의 구성
const [post, setPost] = useState({ id: '', title: '', content: '', }); const [posts, setPosts] = useState([ { id: 1, title: '제목1', content: '내용1' }, { id: 2, title: '제목2', content: '내용2' }, { id: 3, title: '제목3', content: '내용3' }, { id: 4, title: '제목4', content: '내용4' }, { id: 5, title: '제목5', content: '내용5' }, ]);
<form onSubmit={handleWrite}> <input type="text" placeholder="제목을 입력하세요." value={post.title} onChange={handleForm} name="title" /> <input type="text" placeholder="내용을 입력하세요." value={post.content} onChange={handleForm} name="content" /> <button type="submit">글쓰기</button> </form>
ㆍ 위 코드는 사용자로부터 제목과 내용을 입력받기 위한 양식으로 구성되어 있다.
ㆍ 사용자로부터 입력받은 제목, 내용 데이터는 상태 변수인 post에 저장되고, 버튼을 누르면 posts 상태 변수에 해당 데이터가 추가되는 시나리오이다.
입력 데이터의 유지
const handleForm = (e) => { setPost({ ...post, [e.target.name]: e.target.value }); // computed property names 문법 (키값 동적할당) };
ㆍ form 태그 내의 input 태그에 name 속성을 지정해 준다.
ㆍ hadleForm() 함수를 통해 기존의 post 상태 변수에 데이터를 추가한다.
입력 데이터 전달
const handleWrite = (e) => { e.preventDefault(); // form 태그가 하려는 액션을 중지 시킴 setPosts([...posts, post]); };
ㆍ 버튼을 누르면 handleWrite() 함수를 통해 입력 데이터를 posts 상태 변수에 추가한다.
728x90'Framework & Library > React' 카테고리의 다른 글
React 기초 - Redux (0) 2021.09.22 React 기초 - Router (0) 2021.09.22 React 기초 - props (0) 2021.09.22 React 기초 - useRef 함수 (0) 2021.09.22 React 기초 - useMemo 함수 (0) 2021.09.22