所以这个问题在过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中传递函数的一些重要内容?任何帮助都将不胜感激.

推荐答案

你可以这样试试

为子组件添加事件处理程序

export default function childComponent(props: Props){
    return(
        <button onClick={(e) => props.parentFunction(e)}></button>
    )
}

处理程序类型如下所示

type Props = {
   parentFunction: (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => Promise<void>;
}

实际事件处理程序

  const parentFunction = (event: MouseEvent<HTMLButtonElement>: e, email?: string, password?: string, userName?: string) => ...

Typescript相关问答推荐

如何根据数据类型动态注入组件?

忽略和K的定义

使用泛型keyof索引类型以在if-condition内类型推断

为什么在回调函数的参数中不使用类型保护?

如何在Typescript 中组合unions ?

为什么在leetcode问题的测试用例中,即使我确实得到了比预期更好的解决方案,这段代码也失败了?

声明文件中的类型继承

与toast.error一起react 中的Async TUNK错误消息

Angular 16将独立组件作为对话框加载,而不进行布线或预加载

将布尔值附加到每个对象特性

棱角分明-什么是...接口类型<;T>;扩展函数{new(...args:any[]):t;}...卑鄙?

作为函数参数的联合类型的键

在单独的组件中定义React Router路由

在TypeScript中,如何通过一系列过滤器缩小类型?

作为参数的KeyOf变量的类型

如何从JWT Reaction中提取特定值

有没有更干净的方法来更新**key of T**的值?

我的类型谓词函数不能像我预期的那样工作.需要帮助了解原因

映射类型不是数组类型

使用 TypeScript 在 SolidJS 中绘制 D3 力图