[英]How to access this.props in child class in function that overrides parent's function
我想在父函数中定义的this.props.childName
中使用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>
,它只包含属性parentName
。
为了让 PropChildren 作为子组件中的 props 类型,您应该将其声明为:
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)
}
}
为了同时允许正确的 props 定义和从父类派生的子类,您必须在定义中包含 props 类型:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.