关于组件的泛型的请教
来源:8-9 【redux封装】在类组件中使用react-redux

那辰4403872
2022-08-31
type PropsType = RouteComponentProps // react-router 路由props类型
& WithTranslation // i18n props类型
& ReturnType<typeof mapStateToProps> // 映射 redux store 的数据类型
& ReturnType<typeof mapDispatchToProps> // 映射 redux dispatch 的数据类型
class HeaderComponent extends React.Component<PropsType> {...}
老师您好,关于以上代码,我是否可以理解为:只要有第三方插件(或者自己编写的中间件),对这个组件的 props 注入了新的数据:
假设组件的 props 是这样追加/更新的:Object.assign({}, {...插件A, ...插件B ...插件C})
我就得对这些绑定到 props 上的新数据 进行类型推断?
比如,通过 import 导入进来的,就直接加在泛型上
import {RouteComponentProps} from "../../helpers/withRouter";
import {WithTranslation} from "react-i18next";
class HeaderComponent extends React.Component<RouteComponentProps & WithTranslation>
如果是把函数的返回值,传入 柯里化函数 的形参,追加到 props 上的:就通过反向注入,从 ReturnType 的泛型中提取函数返回值的类型 ReturnType<typeof 函数名>
type PropsType = ReturnType<typeof mapStateToProps>
& ReturnType<typeof mapDispatchToProps>
& ReturnType<typeof store.getState>
class HeaderComponent extends React.Component<PropsType>
这样理解对吗?请老师不吝指教
写回答
1回答
-
阿莱克斯刘
2022-09-01
hello 同学,你的理解基本正确,非常开心能看到这么独特的思路,非常棒。虽然不一定所有的函数都需要使用ReturnType<typeof 函数名>来获取类型(例子一下子想不到...😂),但其实我们只需要关注在搭建组件的时候同时引入我们关注的props类型就可以了。不过可能有个错误还是需要留意一下,props的传入应该是引用传参(call by reference),所以react底层在处理组件嵌套过程中应该没有使用object.assign。
10
相似问题