小编典典

如何在React.memo中将Props与泛型一起使用

reactjs

我正在尝试将以下内容转换为使用React.memo

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

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

}

像这样(不正确):

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



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

})

如何更正此语法?当前它有此错误:

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

阅读 1805

收藏
2020-07-22

共1个答案

小编典典

使用当前的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>) => ... */}
  </>
)

操场

2020-07-22