props
에 callback 함수
를 넣어서 호출 받을 수 있다.
Parent
1
2
3
4
5
6
7
8
9
10
const Parent = () => {
const handleItemChanged = (action, item) => {
console.log(action, item);
}
return (
<Child onItemChanged={handleItemChanged} />
)
}
Child
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const Child = ({onItemChanged}) => {
const [items, setItems] = useState([]);
const addItem = () => {
try {
const object = {
'new item'
};
setItems([...items, object]);
// 부모 컴포넌트에 callback 함수 호출
if (onItemChanged) {
onItemChanged('add', object);
}
} catch (e) {
console.log(`Fail to add image.`, e);
}
}
return (
<div>Child</div>
)
};