本文介绍了如何在 React.memo 中使用带有泛型的 Props的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将以下内容转换为使用 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>) {
}
像这样(不正确):
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>>(
~~~~~~~~
推荐答案
使用当前的 React 类型声明,不可能从 React.memo
创建通用组件.没有类型断言的解决方案是添加一个额外的 memo 函数重载以利用 TS 3.4 高阶函数类型推断:
With current React type declarations, it is not possible to create a generic component out of React.memo
. A solution without type assertions is to add an additional memo
function overload to leverage TS 3.4 higher order function type inference:
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
:
You then will be able to make Table
component generic. Just make sure to pass a generic function to 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>) => ... */}
</>
)
这篇关于如何在 React.memo 中使用带有泛型的 Props的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!