如何在功能组件的React中的props中使用泛型? [英] How to use generics in props in React in a functional component?

查看:1084
本文介绍了如何在功能组件的React中的props中使用泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基于类的组件中,我可以轻松地编写一些这样的代码:

In a class based component, I can easily write some code like this:

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中使用泛型,对我有什么建议?

Actually this CollapsableDataList component should be a functional component because it's stateless, but I can't figure out how to write a function component and use generics in props, any advise for me?

推荐答案

您不能创建带有类型注释的功能组件并使之通用.因此,由于未定义T并且您无法在变量级别上定义它,因此将无法使用:

You can't create a functional component with a type annotation and make it generic. So this will NOT work as T is not defined and you can't define it on the variable level:

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

但是,您可以跳过类型注释,并使函数通用并显式键入props.

You can however skip the type annotation, and make the function generic and type props explicitly.

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

这篇关于如何在功能组件的React中的props中使用泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆