SMALL
거쳐야 하는 단계가 적다면 상위 컴포넌트에서 하위 컴포넌트로 콜백함수를 props로 전달하고 하위 컴포넌트에서 해당 콜백함수를 호출해서 props로 전달할 수 있다.
// 부모 컴포넌트
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const [valueFromChild, setValueFromChild] = useState('');
const handleValueChange = (newValue) => {
setValueFromChild(newValue);
};
return (
<div>
<ChildComponent onValueChange={handleValueChange} />
<p>Value from child: {valueFromChild}</p>
</div>
);
}
// 자식 컴포넌트
import React, { useState } from 'react';
function ChildComponent({ onValueChange }) {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
const newValue = event.target.value;
setInputValue(newValue);
onValueChange(newValue); // 부모 컴포넌트의 함수 호출하여 값을 전달
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
}
LIST
'일반' 카테고리의 다른 글
비구조화 할당 문법으로 props 추출 (0) | 2023.08.26 |
---|---|
props - default, children (0) | 2023.08.26 |
Ant Design - Modal (0) | 2023.08.18 |
카카오 지도 API - 버튼 눌러 마커 변경 (0) | 2023.08.14 |
카카오 지도 API - 여러개 마커 표시 (0) | 2023.08.14 |