如何在覆盖父函数的函数中的子类中访问 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
}
}

您的子组件扩展了父组件,父组件中的道具类型为Prop<T>,它只包含属性parentName

为了让PropChildren作为子组件中的道具类型,您应该将其声明为:

class Child<T> extends React.Component< PropChildren<T>, State<T>> {
// ...
}

顺便说一句,您不需要使您的props接口通用(使用<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)
}
}

首先,接口中不需要任何泛型,除非您需要在不同的地方使用它。其次,类Child也应该从React.Component扩展,而不是从其父类扩展。这是一个更好的代码

import React from 'react'
interface IParentProps {
readonly parentName: string;
readonly children?: JSX.Element 
}
interface IPropsChild {
readonly childName: string;
}
class Parent extends React.Component<IParentProps> {
constructor(props: IParentProps) {
super(props)
}
printName = () => {
}
render() {
return <Child childName={this.props.parentName} />
}
}
class Child extends React.Component<IPropsChild> {
constructor(props:IPropsChild) {
super(props)
}
printName = () => {
console.log(this.props.childName)
}
}

为了允许正确的道具定义和从父类派生的子类,您必须在定义中包含道具类型:

interface ParentProp<T> {
parentName: string;
}
export class Parent<T, P = ParentProp<T>, S = {}, SS = any> extends React.Component<P, S, SS> {
public printName() {
// console.log(this.props.parentName); Doesn't compile, as P can be any prop interface.
}
}
interface ChildProp<T> {
childName: string;
}
export class Child<T> extends Parent<T, ChildProp<T>> {
public printName() {
console.log(this.props.childName);
}
}

最新更新