javascript - How to use Props with Generics with 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>) {
}
Like so (incorrect):
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高阶函数类型推断:
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>) => ... */}
</>
)
推荐阅读
- python-3.x - 计算逻辑回归分类器的精度、召回率和 F 度量
- azure - 为什么 BasicLuisDialog.cs 不在网络应用程序机器人的对话框部分?
- php - 如何使用户的个人资料页面可编辑,我想在编辑后保存这些数据(vue.js + laravel)
- qbasic - QB64:使用带有 '$DYNAMIC 的变量类型后缀时出现“重复定义”错误
- javascript - 如果选中复选框即使在页面重新加载时也保持 DIV 隐藏
- javascript - 我的画布上的签名在手机上不起作用
- mysql - 如何在一行中连接两个具有相同列名和不同 ID 的 SQL 表?
- junit4 - 如何为方法编写 Junit 测试用例
- python - WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:502
- r - 创建一个关于summarize+group by的函数