React
react 하위 컴포넌트에서 상위 컴포넌트로 값 전달하는 법
알 수 없는 사용자
2023. 8. 24. 19:26
거쳐야 하는 단계가 적다면 상위 컴포넌트에서 하위 컴포넌트로 콜백함수를 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}
/>
);
}