所以这个问题在过go 的几天里一直困扰着我,我发誓我看到了几乎所有试图解决这个问题的人.我只需要调用从子组件内部的父组件onClick传递的函数.该函数接受参数,参数部分是错误所在.
我知道我可能可以导出和导入该函数,但这是我可以在常规JavaScript中轻松完成并做出react 的事情,所以我相信这一定是可行的.我只是目前还不是最擅长打字的人.
父组件
// Promise Function I am passing to the child
function parentFunction(email: string, password: string, userName: string) {
return promiseFunction(email, password)
.then((result) => {
return updateProfile({
displayName: userName,
})
})
.catch((error) => {
console.log(error);
});
}
// Passing to child component
return (
<div>
<ChildComponent parentFunction = {parentFunction}/>
</div>
)
子组件
因为这是一个onClick函数,我知道我需要处理event
函数.
type Props = {
parentFunction: (event: React.MouseEvent<HTMLButtonElement>) => Promise<void>;
}
export default function childComponent(props: Props){
return(
<button onClick={props.parentFunction}></button>
)
}
类型问题
现在,如果没有参数,那么就不会有问题,并且单击fine时该函数也会工作.然而
函数类型为
parentFunction(email: string, password: string, userName: string): Promise<void>
onClick函数的类型为
MouseEventHandler<HTMLButtonElement>
我try 在Props类型函数中添加参数,但这只满足函数类型问题,onClick
类型问题仍然存在,反之亦然.
我试图解决这个问题
type Props = {
parentFunction: (
email: string,
password: string,
userName: string
event?: React.MouseEvent<HTMLButtonElement>
) => Promise<void>;
}
我做错了吗?我是否完全遗漏了在typescript中传递函数的一些重要内容?任何帮助都将不胜感激.