[ Web ]/React.js
[React.js] Kossie Coder - 14강. 자식 컴포넌트에서 부모 컴포넌트 스테이트 변경하기
HoYoung Kim
2021. 12. 28. 15:42
1. Form 컴포넌트화 (MovieForm.js)
import React, {useState} from "react";
// addMovie 함수를 파라미터로 받음.
const MovieForm = ({addMovie}) => {
const [movieTitle, setMovieTitle] = useState('');
const [movieYear, setMovieYear] = useState('');
// form reset function
const resetForm = () => {
setMovieTitle('');
setMovieYear('');
};
const onSubmit = (event) => {
event.preventDefault();
// 파라미터로 받은 addMovie 함수를 통해 부모의 movies state에 데이터를 추가할 수 있다.
addMovie({
title: movieTitle,
year: movieYear
});
resetForm();
};
return (
<form onSubmit={onSubmit}>
<input
type="text
value={movieTitle}
placeholder="영화제목"
onChange={e => setMovieTitle(e.target.value)}
/><br/>
<input
type="text
value={movieYear}
placeholder="개봉년도"
onChange={e => setMovieYear(e.target.value)}
/><br/>
<button type="submit">영화추가</button>
</form>
);
}
export default MovieForm;
2. 부모 컴포넌트 (App.js)
...
import MovieForm from "./components/MovieForm";
...
const addMovie = (movie) => {
setMovies([
...movies,
movie // 자식 컴포넌트로부터 받은 movie 객체를 현재 movies state에 저장
]);
};
return (
<div className="App">
<MovieForm addMovie={addMovie}/>
{renderMovies}
</div>
);
...
강의 링크