我正在尝试将以下内容转换为使用React.memo:
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>>( ~~~~~~~~
使用当前的React类型声明,无法从中创建通用组件React.memo。没有类型声明的解决方案是添加一个附加的memo函数重载以利用TS 3.4 高阶函数类型推断:
memo
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:
Table
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>) => ... */} </> )
操场