javascript - 如何在覆盖父函数的函数中访问子类中的 this.props
问题描述
我想this.props.childName
在父函数中定义的子函数中使用。但它是 TypeScript 编译错误 ( Property 'name' does not exist...
) 如果我使用this.props.parentName
,就可以了。如何访问this.props
子类?
interface Prop<T> {
parentName: string
}
class Parent<T> extends React.Component<Prop<T>, State<T>> {
constructor(props: Prop<T>) {
super(props)
}
printName() {}
}
interface PropChildren<T> {
childName: string
}
class Child<T> extends Parent<string> {
constructor(props: PropChildren<T>) {
super(props)
}
printName() {
console.log(this.props.childName) // here I want to use children prop but compile error
}
}
解决方案
你的子组件扩展了父组件,而父组件中的 props 类型是Prop<T>
,其中只包含 property parentName
。
为了让 PropChildren 作为子组件中的道具类型,您应该将其声明为:
class Child<T> extends React.Component< PropChildren<T>, State<T>> {
// ...
}
顺便说一句,您不需要使您的道具接口通用(使用<T>
)。仅当接口可以在具有不同数据类型的不同上下文中使用时才使用泛型。
根据您的评论,这是一个示例,说明您如何与孩子分享父母的行为,但仍然能够为孩子的道具定义不同的数据类型:
interface PropParent {
parentName: string
}
class Parent<TProp extends PropParent> extends React.Component<TProp, State> {
constructor(props: TProp) {
super(props)
}
printName() {}
}
interface PropChildren extends PropParent {
childName: string
}
class Child<T> extends Parent<PropChildren> {
constructor(props: PropChildren) {
super(props)
}
printName() {
console.log(this.props.childName)
}
}
推荐阅读
- javascript - react js播放本地MP3文件
- jquery - jQuery - 删除具有特定值的表 col
- r - 循环遍历数据帧的行并将其用作 r 中的函数输入
- python - 已经定义为 int 但仍确定为 NoneType
- macos - AppleScript - 预期行尾等。但找到类名(-2741)
- kivy - 如何使用 IDE 导入 kivy
- c# - 为什么 Automapper 在映射列表时返回 null
在 aspnet.core 3.1 中? - python - Python 的拓扑数据分析 (TDA) 映射器
- java - 未找到导入“google/protobuf/timestamp.proto”或有错误
- python - 采样 pandas DF 以匹配错误内的第二个 DF