reactjs - 如何避免使用 Typescript 在 React 构造函数中重新声明道具类型
问题描述
假设我有这样的课程:
class PeopleByTag extends React.Component<RouteComponentProps<{ tag: string }>
我需要在我的构造函数中做一些事情,在这个例子中获取数据,但要做到这一点,我需要声明一个 props 参数,但如果我不指定类型,它将变成任何:
constructor(props) {
super(props); // props is any
this.loadData();
}
另一方面,如果我重新声明类型,代码会变得非常难看:
constructor(props: Readonly<{
children?: React.ReactNode;
}> & Readonly<RouteComponentProps<{
tag: string;
}, StaticContext, any>>) {
super(props);
this.loadData();
}
有没有办法从类扩展中自动推断道具类型,同时还可以编写构造函数?
我也不想使用已弃用的生命周期挂钩(即 ComponentWillMount)。
解决方案
通常constructor
它本身不应该变得“非常难看”,因为类型可以单独定义,type
或者interface
在参数类型冗长的情况下。
props
无法推断构造函数参数,因为React.Component<RouteComponentProps<{ tag: string }>>
泛型参数指的是父类,React.Component
而不是当前类。
从类型定义中可以看出,这为父构造函数推断出正确的类型,即super
.
所以这
constructor(props) {
super(props);
}
已验证。this.props
仍然正确键入。
如果noImplicitAny
使用编译器选项,则为:
constructor(props: any) {
super(props);
}
在构造函数中使用props
typed asany
可能会导致类型错误:
constructor(props: any) {
super(props);
props.tag; // ok
props.nonexistentProp; // ok
}
Whilethis.props
是类型安全的。
可以将一个类作为泛型进行类型化,以在构造函数中维护正确的 props 类型,但这可能被认为是矫枉过正:
export class PeopleByTag<P extends { tag: string }> extends React.Component<P> {
constructor(props: Readonly<P>) {
super(props); // props is any
props.tag; // ok
props.nonexistentProp; // not ok
props.children; // not ok, but we rarely ever need children in constructor
}
}
props
通过为其提供不兼容的类型来防止使用 in 构造函数可能是有益的:
constructor(props: never) {
super(props);
props.tag; // not ok
}
如果props
参数被传递给super
,this.props
并且props
在 JavaScript 中是可互换的。它们在 TypeScript 中不可互换。this.props
可以在构造函数中访问正确类型的道具。
推荐阅读
- python - Python:如何使用正则表达式仅选择括号内的某些整数
- javascript - 图像存储在本地并预加载,但加载速度仍然很慢
- numpy - 在基于 ARM 处理器 32 位的 Ubuntu 操作系统上安装机器学习包
- r - 如何将元素与嵌套向量列匹配?
- excel - 了解 If Err.Number 的使用
- c# - 我无法使用 HttpClientMultipartFormDataContent 模拟 HTML 表单帖子
- tensorflow - tensorflowjs 的 WebGL 后端很晚才加载模型(blazeface)
- java - JDK 11 迁移 - 无法解析类型 javax.xml.namespace.QName。它是从所需的 .class 文件中间接引用的
- r - 由于导入功能而导致 Crontab R 脚本失败(Rstudio 已关闭)
- python - 如何搜索数组并找到用户输入的项目?(在 Python 中)