React + TypeScript 实现泛型组件
泛型类型TypeScript 中,类型(interface, type)是可以声明成泛型的,这很常见。 interface Props<T> {content: T; } 这表明
type StringProps = Props<string>;let props: StringProps;props = {// ? Type 'number' is not assignable to type 'string'.ts(2322)content: 42 };props = {// ✅content: "hello" }; 或者,TypeScript 能够跟使用时候提供的值自动推断出类型 interface Props<T> {content: T; }function Foo<T>(props: Props<T>) {console.log(props); }/** 此时 Foo 的完整签名为: function Foo<number>(props: Props<number>): void */ Foo({ content: 42 });/** 此时 Foo 的完整签名为: function Foo<string>(props: Props<string>): void */ Foo({ content: "hello" }); 上面因为 当调用 function Foo<number>(props: Props<number>): void; 而我们并没有显式地指定其中的类型 泛型组件将上面的 function Foo<T>(props: Props<T>) {return <div> {props.content}</div>; }const App = () => {return (<div className="App"><Foo content={42}></Foo><Foo<string> content={"hello"}></Foo></div>); }; 一如上面的讨论,因为 TypeScript 可根据传入的实际值解析泛型类型,所以 为了进一步理解泛型组件,再看下非泛型情况下上面的组件是长怎样的。 interface Props {content: string; }function Foo(props: Props) {return <div>{props.content}</div>; }const App = () => {return (<div className="App">{/* ? Type 'number' is not assignable to type 'string'.ts(2322) */}<Foo content={42}></Foo><Foo content={"hello"}></Foo></div>); }; 以上,便是一个 React 组件常规的写法。它定义的入参 除了函数组件,对于类类型的组件来说,也是一样可泛型化的。 interface Props<T> {content: T; }class Bar<T> extends React.Component<Props<T>> {render() {return <div>{this.props.content}</div>;} }const App = () => {return (<div className="App"><Bar content={42}></Bar><Bar<string> content={"hello"}></Bar></div>); }; 一个更加真实的示例一个更加实用的示例是列表组件。列表中的分页加载,滚动刷新逻辑等,对于所有列表数据都是通用的,将这个列表组件书写成泛型便可和任意类型列表数据结合,而无须通过其他方式来达到复用的目的,将列表元素声明成 先看不使用泛型情况下,如何实现这么一个列表组件。此处只看列表元素的展示以阐述泛型的作用,其他逻辑比如数据加载等先忽略。 列表组件 List.tsx interface Item {[prop: string]: any; }interface Props {list: Item[];children: (item: Item, index: number) => React.ReactNode; }function List({ list, children }: Props) {// 列表中其他逻辑...return <div>{list.map(children)}</div>; } 上面,为了尽可能满足大部分数据类型,将列表的元素类型定义成了 然后是使用上面所定义的列表组件: interface User {id: number;name: string; } const data: User[] = [{id: 1,name: "wayou"},{id: 1,name: "niuwayong"} ];const App = () => {return (<div className="App"><List list={data}>{item => {// ? 此处 `item.name` 类型为 `any`return <div key={item.name}>{item.name}</div>;}}</List></div>); }; 这里使用时, 上面的实现还有个问题是它规定了列表元素必需是对象,理所应当地就不能处理元始类型数组了,比如无法渲染 下面使用泛型改造上面的列表组件,让它支持外部传入类型。 interface Props<T> {list: T[];children: (item: T, index: number) => React.ReactNode; }function List<T>({ list, children }: Props<T>) {// 列表中其他逻辑...return <div>{list.map(children)}</div>; } 改造后,列表元素的类型完全由使用的地方决定,作为列表组件,内部它无须关心,同时对于外部传递的 使用改造后的泛型列表: interface User {id: number;name: string; } const data: User[] = [{id: 1,name: "wayou"},{id: 1,name: "niuwayong"} ];const App = () => {return (<div className="App"><List list={data}>{item => {// ? 此处 `item` 类型为 `User`return <div key={item.name}>{item.name}</div>;}}</List><List list={["wayou", "niuwayong"]}>{item => {// ? 此处 `item` 类型为 `string`return <div key={item}>{item}</div>;}}</List></div>); }; |
转载于:https://www.cnblogs.com/Wayou/p/react_typescript_generic_components.html
React + TypeScript 实现泛型组件相关推荐
- React组件库实践:React + Typescript + Less + Rollup + Storybook
背景 原先在做低代码平台的时候,刚好有搭载React组件库的需求,所以就搞了一套通用的React组件库模版.目前通过这套模板也搭建过好几个组件库. 为了让这个模板更干净和通用,我把所有和低代码相关的代 ...
- React + TypeScript实战(二)hooks用法
本文采用的react相关技术为: react@18.2.0 typescript@4.7.4 脚手架create-react-app 一.函数式组建的声明方式 import react, { FC } ...
- 字节 React + TypeScript 实践总结篇
❗️ 准备知识 熟悉 React 熟悉 TypeScript (参考书籍:2ality's guide[1], 初学者建议阅读:chibicode's tutorial[2]) 熟读 React 官方 ...
- 【实战】1060- 字节 React + TypeScript 实践
❗️ 准备知识 熟悉 React 熟悉 TypeScript (参考书籍:2ality's guide[1], 初学者建议阅读:chibicode's tutorial[2]) 熟读 React 官方 ...
- React + Typescript + Webpack 开发环境配置
对于复杂或多人开发的 React 项目来说,管理和使用每个组件的 props . state 或许会成为一件让人头痛的事情,而为每一个组件写文档,成本也会比较大,对项目的开发效率也不是最理想的. Ty ...
- Webpack 4 + React + Typescript 搭建启动模版
2019年是个崭新的开始,在过去半年的工作中我参与到公司一个大型项目的维护和开发中,深深的体会到了react项目中数据流向复杂,参数类型错乱带来的痛苦体验,于是在崭新的一年我决定拥抱Typescrip ...
- React + TypeScript:元素引用的传递
React 中需要操作元素时,可通过 findDOMNode() 或通过 createRef() 创建对元素的引用来实现.前者官方不推荐,所以这里讨论后者及其与 TypeScript 结合时如何工作. ...
- React + TypeScript 默认 Props 的处理
React 中的默认 Props 通过组件的 defaultProps 属性可为其 Props 指定默认值. 以下示例来自 React 官方文档 - Default Prop Values: clas ...
- React+TypeScript+webpack4多入口项目搭建
资源 React-16.8.* react-router-dom-4.3.* TypeScript-3.5.* webpack-4.* eslint-5.16.* 项目目录 ├── dist # 打包 ...
最新文章
- 偏依赖图(Partial Dependence Plots)是什么?排列重要性(Permutaion Importance)是什么?如何解读?有什么意义?
- 揭秘数字行为:快速地多次点击
- linux内核态real cred,Linux内核实验报告——实验5.doc
- 20. C# -- Base, this 关键字
- Linux RTC 驱动实验
- React-router的基本使用
- 第四十一期:一道经典的MySQL面试题,答案出现三次反转
- C语言中printf输出特殊字符(“%d“或者“\n“)
- 最小生成树——普里姆算法和克鲁斯卡尔算法
- centos7 ifconfig命令找不到_Linux基础命令大全,你找不到的这都有
- 凤凰号首次传回未加工的火星照片,人类加紧施展征服火星计划
- USB手机数据线充电线电源线出口办理CE认证的流程
- android连接服务器代码实例,Android客户端连接服务器端,向服务器端发送请求HttpURLConnection(示例代码)...
- word 批量把参考文献的交叉引用变成上标形式
- python将数据导入数据库 atomic_Python3 连接 Sqlite3
- APP渗透—Android 7.0 抓包(教程)
- shell连接CentOS启动可视化界面startx
- 解读|Cocos新平台、新生态的行业意义
- FPGA并行计算可编程芯片
- 高中选科策略隐私政策