我想将React memo用于具有通用参数的函数。不幸的是,泛型参数默认为泛型,所有奇特的泛型推导逻辑都丢失了(TypeScript v3.5.2)。在下面的示例中WithMemo(使用React.memo)失败,原因:
Property 'length' does not exist on type 'string | number'.
Property 'length' does not exist on type 'number'.
Run Code Online (Sandbox Code Playgroud)
而WithoutMemo作品如预期的那样。
interface TProps<T extends string | number> {
arg: T;
output: (o: T) => string;
}
const Test = <T extends string | number>(props: TProps<T>) => {
const { arg, output } = props;
return <div>{output(arg)} </div>;
};
const myArg = 'a string';
const WithoutMemo = <Test arg={myArg} output={o => …Run Code Online (Sandbox Code Playgroud) 在基于类的组件中,我可以轻松地编写如下代码:
import * as React from 'react';
import { render } from 'react-dom';
interface IProps<T> {
collapsed: boolean;
listOfData: T[];
displayData: (data: T, index: number) => React.ReactNode;
}
class CollapsableDataList<T> extends React.Component<IProps<T>> {
render () {
if (!this.props.collapsed) {
return <span>total: {this.props.listOfData.length}</span>
} else {
return (
<>
{
this.props.listOfData.map(this.props.displayData)
}
</>
)
}
}
}
render(
<CollapsableDataList
collapsed={false}
listOfData={[{a: 1, b: 2}, {a: 3, b: 4}]}
displayData={(data, index) => (<span key={index}>{data.a + data.b}</span>)}
/>,
document.getElementById('root'),
)
Run Code Online (Sandbox Code Playgroud)
实际上这个CollapsableDataList组件应该是一个功能组件,因为它是无状态的,但是我无法弄清楚如何编写一个函数组件并在道具中使用泛型,对我有什么建议吗?
我正在尝试将以下内容转换为使用React.memo:
interface Props<TRowData> {
// props...
}
export function Table<TRowData>({
propA,
propB
}: Props<TRowData>) {
}
Run Code Online (Sandbox Code Playgroud)
像这样(不正确):
interface Props<TRowData> {
// props...
}
export const Table = memo<Props<TRowData>>(
({
propA,
propB
}) => {
})
Run Code Online (Sandbox Code Playgroud)
如何更正此语法?目前它有这个错误:
// Cannot find name 'TRowData'.
export const Table = memo<Props<TRowData>>(
~~~~~~~~
Run Code Online (Sandbox Code Playgroud)