|
|
飞奔的灯泡 · 【机器学习3】鸢尾花数据集可视化,让枯燥的数 ...· 1 年前 · |
|
|
慈祥的苹果 · 凌犀LZ6000工业电脑主机 台式机 ...· 1 年前 · |
|
|
从容的柚子 · 历史解密:迷彩服是怎么被发明出来的?现在军人 ...· 2 年前 · |
|
|
打篮球的手电筒 · 胡锡进:被川建国比作“笔尖” ...· 2 年前 · |
|
|
发呆的洋葱 · 新力量在积蓄 ...· 2 年前 · |
我正在尝试将以下代码转换为使用
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> {
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: