首页 > 解决方案 > 如何在带有 RefForwardingComponent 的反应函数组件中使用泛型?

问题描述

当我在反应中使用 forwardRef 时,我的代码如下:

interface FProps<P, T> {
    name: P
    birth: T
}

interface Handler {}

const Comp: RefForwardingComponent<Handler, FProps<P, T>> = <P, T>(
    { name, birth }: FProps<P, T>,
    ref
) => {

    useImperativeHandle(ref, () => ({
        name
  }))
  
    return <div>{name}</div>
}

export default forwardRef(Comp)

但我得到了:

在此处输入图像描述

如何解决这个问题呢?

标签: reactjstypescriptreact-hooks

解决方案


泛型P取决于函数的参数,并且仅在调用函数时才知道,因此您不能使用它来定义函数本身。相反,我们必须定义参数:

const Comp = <P, T>(
    { name, birth }: FProps<P, T>,
    ref: ((instance: Handler | null) => void) | MutableRefObject<Handler | null> | null,
) => {
...

游乐场链接


推荐阅读