const [tweets, setTweets] = useState(...생략);
const addNewTweet = (newTweet) => {
setTweets([...tweets, newTweet]);
}; // 이 함수(addNewTweet)가 자식 컴포넌트에 의해 실행되어야 한다
return
<div>
<NewTweetForm 보내는 함수={addNewTweet}/>
</div>
function NewTweetForm({ 보내는 함수 }) {
...생략
}
const [newTweetContent, setNewTweetContent] = useState("");
const onTextChange = (e) => {
setNewTweetContent(e.target.value);
};
7-1) 부모 컴포넌트에서 받아온 함수(=보내는 함수)를 호출하는 함수를 만든다.
const onClickSubmit = () => {
보내는 함수() //부모 컴포넌트의 함수 호출
};
7-2) 변경된 데이터가 반영된 state를 '새로운 변수(newTweet)'에 담는다
const onClickSubmit = () => {
let newTweet = {
uuid: Math.floor(Math.random() * 10000),
writer: currentUser,
date: new Date().toISOString().substring(0, 10),
content: newTweetContent
};
보내는 함수() //부모 컴포넌트의 함수 호출
};
7-3) 함수로 '새로운 변수(newTweet)'를 전달한다
const onClickSubmit = () => {
let newTweet = {
uuid: Math.floor(Math.random() * 10000),
writer: currentUser,
date: new Date().toISOString().substring(0, 10),
content: newTweetContent
};
보내는 함수(newTweet)
//부모 컴포넌트의 함수 호출
//newTweet를 addNewTweet(부모컴포넌트)에 전달
};
<button id="submit-new-tweet" onClick={onClickSubmit}>
버튼
</button>
버튼을 클릭할 때마다 newTweetContent(변경된 데이터)가 포함된 newTweet이라는 변수(데이터)가 '보내는 함수'로 전달된다.
부모 컴포넌트에서의 데이터 흐름
addNewTweet(newTweet) -> setTweets([...tweets, newTweet])