
Sharing State Between Components – React
Lifting state up
상태를 하위 컴포넌트에 전달
상태 변경 함수를 하위 컴포넌트에 전달
import React, { useState } from 'react';
import ChildButton from './ChildButton';
import ChildInput from './ChildInput';
const Parent = () => {
const [id, setId] = useState('');
const [password, setPassword] = useState('');
const handleConfirm = () => {
console.log(`${id} ${password} 확인을 눌렀습니다.`);
};
const handleCancel = () => {
console.log('취소를 눌렀습니다.');
};
return (
<>
<ChildInput type="text" value={id} func={setId} />
<ChildInput type="password" value={password} func={setPassword} />
<ChildButton label="확인" func={handleConfirm} />
<ChildButton label="취소" func={handleCancel} />
</>
);
};
export default Parent;
하위 컴포넌트의 상태 변화 또는 이벤트를 다시 상위 컴포넌트에 리턴
import React from 'react';
interface Props {
type: string;
value: string;
func: (value: string) => void;
}
const ChildInput = ({ type, value, func }: Props) => {
// const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
// func(e.target.value);
// };
return <input type={type} value={value} onChange={(e) => func(e.target.value)} />;
};
export default ChildInput;
import React from 'react';
interface Props {
label: string;
func: () => void;
}
const ChildButton = ({ label, func }: Props) => {
return <button onClick={func}>{label}</button>;
};
export default ChildButton;

