React Typescript:将函数作为带有参数的道具传递

React Typescript: Pass function as props with arguments

所以这个问题在过去几天一直笼罩着我,我发誓我看到几乎每个人都在努力解决它。我只需要在子组件内部调用从父组件 onClick 传递的函数。函数接受参数,参数部分是错误所在。

我知道我可能可以导出和导入函数,但这是我可以在常规 JavaScript 中轻松完成并做出反应的事情,所以我确信它一定是可行的。目前我还不是最擅长 TypeScript 的人。

父组件

// 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>
    )
}

类型问题

现在,如果没有参数,就不会有问题,并且该函数可以在单击时正常运行。然而

函数类型

parentFunction(email: string, password: string, userName: string): Promise<void>

onClick函数是

类型
MouseEventHandler<HTMLButtonElement>

我试过在 Props 类型函数中添加参数,但只能解决函数类型问题, onClick 类型问题仍然存在,反之亦然。

我解决问题的尝试

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

我做错了吗?我是否完全遗漏了一些对于在打字稿中传递函数至关重要的东西?任何帮助将不胜感激。

你可以这样试试

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

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) => ...