【发布时间】:2021-11-10 11:12:31
【问题描述】:
我正在尝试从子组件更新父组件的状态。我在 Props 接口中传递了一个函数,但我似乎无法使用我的 clickHandler 调用它。
父组件中有用户信息,应该从组成注册的各种小组件更新。
这似乎是正确的方法吗?
App.tsx
const updateName = (
e: React.MouseEvent, // Function to update parent state
firstName: string, // Triggered by child components
lastName: string
) => {
setFirstName(firstName);
setLastName(lastName);
};
使用此函数作为道具渲染组件:
<FullName
firstName={""}
lastName={""}
updateName={(e, first: string, last: string) =>
updateName(e, first, last)
}
/>;
在 ChildComponent.tsx 中
这是道具界面:
interface NameProps {
firstName: string;
lastName: string;
updateName: (e: React.MouseEvent, first: string, last: string) => void;
}
这是我要调用函数的地方,以便将状态数据从子级发送到父级,作为 updateName 中的参数!
function handleClick(e: React.FormEvent<HTMLButtonElement>) {
console.log(first, last);
// I want to call NameProps.updateName here
}
如果这完全是错误的方法,请告诉我,但我似乎非常接近。
【问题讨论】:
标签: reactjs typescript components