Reactjs 从react组件继承
您好,我使用的是typescript+react,我希望有一个基类和几个组件继承自基类Reactjs 从react组件继承,reactjs,typescript,typescript2.0,Reactjs,Typescript,Typescript2.0,您好,我使用的是typescript+react,我希望有一个基类和几个组件继承自基类 import * as React from "react"; interface IBaseProps { title: string; } class Base<P extends IBaseProps, S> extends React.Component<P, S> { public props: IBaseProps; public render
import * as React from "react";
interface IBaseProps {
title: string;
}
class Base<P extends IBaseProps, S> extends React.Component<P, S> {
public props: IBaseProps;
public render() {
return (
<h1> Generic Class {this.props.title} </h1>
);
}
}
interface IChildProps extends IBaseProps {
message: string;
}
class Child extends React.Component<IChildProps, undefined> {
public render() {
return (
<h1> Child Class {this.props.title} {this.props.message} </h1>
);
}
}
import*as React from“React”;
接口IBaseProps{
标题:字符串;
}
类基扩展React.Component{
公共道具:IBaseProps;
公共渲染(){
返回(
泛型类{this.props.title}
);
}
}
接口IChildProps扩展了IBaseProps{
消息:字符串;
}
子类扩展了React.Component{
公共渲染(){
返回(
子类{this.props.title}{this.props.message}
);
}
}
但编译时会抛出一个错误:
TS2415: Class 'Base<P, S>' incorrectly extends base class 'Component<P, S>'.
Types of property 'props' are incompatible.
Type 'IBaseProps' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly<P>'.
Type 'IBaseProps' is not assignable to type 'Readonly<P>'.
TS2415:类“Base”错误地扩展了基类“Component”。
属性“props”的类型不兼容。
类型“IBaseProps”不可分配给类型“Readonly&Readonly”。
类型“IBaseProps”不可分配给类型“Readonly
”。
问题不在于继承,即使这让我犯了错误
export class Base<P, S> extends React.Component<P, S> {
public props: IBaseProps;
public render() {
return (
<h1> Generic Component </h1>
);
}
}
导出类基扩展React.Component{
公共道具:IBaseProps;
公共渲染(){
返回(
通用组件
);
}
}
我使用的是typescript
v2.3.4
,如果这很重要的话不需要定义两次props
成员,在基类中这样做就足够了:
class Base<P extends IBaseProps, S> extends React.Component<P, S> {
public props: IBaseProps;
...
}
class Child extends React.Component<IChildProps, undefined> {
public render() {
...
}
}
而且您在所有组件中仍然会有this.props
(使用正确的类型)
编辑 在原始代码中,您有以下内容:
class Base<P extends IBaseProps, S> extends React.Component<P, S> {
public props: IBaseProps;
...
}
class Base扩展React.Component{
公共道具:IBaseProps;
...
}
但其定义是:
类组件{
...
道具:只读&只读;
...
}
这意味着您已使用不匹配的类型覆盖了
props
成员,这就是错误说明的内容。与回答您的问题无关。但通常不鼓励继承人这样做。看看Dan的回答我做了一点研究,我做的应该行得通,知道为什么不行吗?你在最后一段代码中得到的错误是什么?我得到了相同的错误如果你不使用IBaseProps
,你就不能得到相同的错误。抱歉,这对我没有帮助,我复制了道具,但在删除它之后,这个错误仍然是我的错误,这可以解决它,但我仍然不知道为什么
class Base<P extends IBaseProps, S> extends React.Component<P, S> {
public props: IBaseProps;
...
}
class Component<P, S> {
...
props: Readonly<{ children?: ReactNode }> & Readonly<P>;
...
}