[英]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.