在基于类的组件中,我可以轻松编写如下代码:

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'),
)

实际上,这个CollapsableDataList组件应该是一个功能组件,因为它是无状态的,但我不知道如何编写一个功能组件,如何在props 中使用泛型,有什么建议吗?

推荐答案

不能创建带有类型注释的功能组件并将其设置为泛型.所以这不起作用,因为没有定义T,也不能在变量级别定义它:

const CollapsableDataList : React.FunctionComponent<IProps<T>> = p => { /*...*/ } 

但是,您可以跳过类型注释,并显式地将函数设置为泛型和类型props.

import * as React from 'react';
import { render } from 'react-dom';

interface IProps<T> {
    collapsed: boolean;
    listOfData: T[];
    displayData: (data: T, index: number) => React.ReactNode;
}
const CollapsableDataList = <T extends object>(props: IProps<T> & { children?: ReactNode }) => {
    if (!props.collapsed) {
        return <span>total: {props.listOfData.length}</span>
    } else {
        return (
            <>
                {
                    props.listOfData.map(props.displayData)
                }
            </>
        )
    }
}


render(
    <CollapsableDataList
        collapsed={false}
        listOfData={[{a: 1, b: 2}, {a: 3, c: 4}]}
        displayData={(data, index) => (<span key={index}>{data.a + (data.b || 0)}</span>)}
    />,
    document.getElementById('root'),
)

Typescript相关问答推荐

如何使用另一个类型的属性中的类型

Typescript对每个属性具有约束的通用类型

使用ngrok解析Angular 时出现HTTP故障

如何编写一个类型脚本函数,将一个对象映射(转换)为另一个对象并推断返回类型?

如何表示多层深度的泛型类型数组?

类型脚本映射类型:从对象和字符串列表到键值对象

在对象中将缺省值设置为空值

在Reaction-Native-ReAnimated中不存在Animated.Value

如何在NX工作区项目.json中设置类似angular.json的两个项目构建配置?

正交摄影机正在将渲染的场景切成两半

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

如何从一个泛型类型推断多个类型

NPM使用Vite Reaction应用程序运行预览有效,但我无法将其部署到Netlify

在构建Angular 应用程序时,有没有办法通过CLI传递参数?

字符串文字联合的分布式条件类型

Rxjs将省略的可观测对象合并到一个数组中

为什么类型脚本使用接口来声明函数?他的目的是什么.

在TS泛型和记录类型映射方面有问题

我可以将一个类型数组映射到TypeScrip中的另一个类型数组吗?

如何让Record中的每个值都有独立的类型?