首页 > 其他分享 >[Typescript + React] Tip: Use generics in React to make dynamic and flexible components

[Typescript + React] Tip: Use generics in React to make dynamic and flexible components

时间:2022-10-07 18:22:50浏览次数:61  
标签:Use Typescript name make dynamic React generics flexible

You can use generics in React to make incredibly dynamic, flexible components. Here, I make a Table component with a generic 'items' type.


interface TableProps<TItem> {
    items: TItem[]
    renderItem: (item: TItem) => React.ReactNode
}

export function Table<TItem>(props: TableProps<TItem>) {
    return null
}

type TableItem = {id: number; name: string}

const Component = () => {
    return (
        <Table<TableItem>
            items={[
                {
                    id: 1,
                    name: 'Jon',
                },
            ]}
            renderItem={(item) => <div>{item.name}</div>}
        ></Table>
    )
}

 

标签:Use,Typescript,name,make,dynamic,React,generics,flexible
From: https://www.cnblogs.com/Answer1215/p/16760220.html

相关文章