我正在尝试将以下代码转换为使用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>>(
~~~~~~~~
发布于 2020-02-25 15:03:40
使用当前的React类型声明,不可能在React.memo
之外创建泛型组件。没有类型断言的解决方案是添加额外的memo
函数重载以利用TS3.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
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-02-25 11:04:25
我通过将其保留为一个函数来解决它,将该函数重命名为TableComponent
并执行以下操作:
export const Table = memo(TableComponent) as typeof TableComponent
编辑,这也行得通:
const typedMemo: <T>(c: T) => T = React.memo
export const Table = typedMemo(TableComponent)
发布于 2020-02-25 11:00:57
您不需要将组件作为React.memo
的第一个参数传递吗?我不能测试它,但我觉得这是思考的过程:
// Overall format:
export const Table = memo(MyComponent, MyFunction)
// With empty arrow function:
export const Table = memo(MyComponent, () => {})
// With your code:
export const Table = memo(MyComponent, ({propA, propB}: Props<TRowData>) => {
})
https://stackoverflow.com/questions/60386614
复制相似问题