src/components/User.tsx
export default function User(props: {
userObj: { name: string; age: number; };
clickHandler: () => void; ----- ➊
}) {
return (
<>
<p>name: {props.userObj.name}</p>
<p>age: {props.userObj.age}</p>
<button onClick={props.clickHandler}>클릭</button> ----- ➋
</>
);
}
➊ clickHandler() 타입은 매개변수도 없고(()) 반환 값도 없는(void) 함수이므로 () => void로 지정합니다.
➋ 버튼의 onClick 이벤트에 props.clickHandler를 연결합니다. 그러면 버튼을 클릭할 때 부모 컴포넌트에서 정의한 clickHandler() 함수가 실행됩니다.
애플리케이션을 실행한 뒤 웹 브라우저에서 버튼을 클릭하면 콘솔에 다음과 같이 출력됩니다.