React의 Component는 단방향 구조임
App > DiaryEditor
App > DiaryList
구조인데, DiaryEditor -> DiaryList 로 데이터를 넘겨주고 싶다면,
1. App의 state로 data와 setData를 만든다 -> onCreate함수에 setData를 넣음
2. DiaryEditor에게 props로 onCreate를 넘겨준다. -> DiaryEditor가 onCreate를 통해 data를 추가한다
첫번째로, App의 state로 data와 setData를 만들어보겠습니다.
1. const [data,setData]=useState([ ]) ; state변수 data와 data를 변경할 함수 setData, data의 초기값 useState([ ])로 설정해줍니다.
2. dataId = userRef(0)으로 dataId의 초기값을 0으로, Ref를 만든다.
3. onCreate함수를 만든다. 이 때, DiaryEditor로부터 인수로 author, content, emotion을 전달받는다.
const onCreate = (author,content,emotion) => { const created_data = ~; const newItem = { author, content, emotion, created_data, id: dataId.current,)
4. newItem과 기존 데이터 ...data를 이어붙힌다.
setData([newItem, ...data])
5. DiaryEditor에게 props로 onCreate를 넘겨준다.
<DiaryEditor onCreate = {onCreate} />
function App() {
const [data, setData] = useState([]);
// state로 data, setData설정
const dataId = useRef(0);
const onCreate = (author, content, emotion) => {
const created_data = new Date().getTime();
const newItem = {
author,
content,
emotion,
created_data,
id: dataId.current,
};
dataId.current += 1;
setData([newItem, ...data]);
// newItem뒤에 원래데이터 ...data를 이어서 붙힘
};
return (
<div className="App">
<DiaryEditor onCreate={onCreate} />
<DiaryList diaryList={data} />
</div>
);
}
export default App;
두번째로, DiaryEditor에서 '일기 저장하기'버튼을 누르면 실행되는 함수 handleSubmit에 저장이 성공하면 onCreate함수를 실행하여 App의 data를 변경하겠습니다.
const handleSubmit = () => { onCreate(state.author, state.content, state.emotion) }
const [state, setState] = useState({
author: "",
content: "",
emotion: 1,
});
const handleSubmit = () => {
onCreate(state.author, state.content, state.emotion);
alert("저장 성공");
setState({
author: "",
content: "",
emotion: 1,
});
};
'WebProgramming > React' 카테고리의 다른 글
[React] MyButton을 만들어 재활용하기 (0) | 2022.07.07 |
---|---|
[React] 라우팅(react-router-dom)(useParams, Query) (0) | 2022.07.07 |
[React] Hook (0) | 2022.07.07 |
[React] 부모 Component -> 자식 Component에게 함수/리스 전달하기 (0) | 2022.07.04 |
[React] List Rendering (0) | 2022.07.03 |
[React] useRef를 이용한 DOM조작 (0) | 2022.07.03 |
[React] React 프로젝트 - DiaryEditor Component (0) | 2022.07.01 |
[React] Props (0) | 2022.07.01 |