首页 > 解决方案 > How to use Props with Generics with React.memo

问题描述

I am trying to convert the following to use React.memo:

interface Props<TRowData> {
  // props...
}

export function Table<TRowData>({
  propA,
  propB
}: Props<TRowData>) {

}

Like so (incorrect):

interface Props<TRowData> {
  // props...
}



export const Table = memo<Props<TRowData>>(
({
  propA,
  propB
}) => {

})

How can I correct this syntax? Currently it has this error:

// Cannot find name 'TRowData'.
export const Table = memo<Props<TRowData>>(
                                ~~~~~~~~

标签: javascriptreactjstypescript

解决方案


使用当前的 React 类型声明,不可能从React.memo. 没有类型断言的解决方案是添加额外的memo函数重载以利用 TS 3.4高阶函数类型推断

import React, { memo } from "react"

declare module "react" { // augment React types
  function memo<A, B>(Component: (props: A) => B): (props: A) => ReactElement | null
  // return type is same as ReturnType<ExoticComponent<any>>
}

然后,您将能够使Table组件通用。只需确保将通用函数传递给memo

interface Props<T> {
  a: T
}

const TableWrapped = <T extends {}>(props: Props<T>) => <div>{props.a}</div>

const Table = memo(TableWrapped)

const App = () => (
  <>
    <Table a="foo" /> {/* (props: Props<string>) => ... */}
    <Table a={3} /> {/* (props: Props<number>) => ... */}
  </>
)

操场


推荐阅读