如何解决抽象通用反应类缺少道具
我对 React 抽象泛型类有疑问。 当我声明一个时,子类上缺少道具,可能我做错了一般性的错误。 主要问题是
Type '{ moving: "no"; }' is not assignable to type 'Readonly<AbCarState & S>'
我想做什么: 使用默认的道具、状态和方法来创建可以通用的类来扩展它并创建可以更改它的新类。
import React from "react";
import { render } from "react-dom";
interface AbCarProps {
color: string;
}
interface AbCarState {
moving: string;
}
abstract class Car<P,S> extends React.Component<AbCarProps,AbCarState> {
constructor(props: P & AbCarProps) {
super(props);
this.state = {
moving: "no"
}
}
}
interface CarProps {
tires: number;
}
interface CarState {
movingFast: string;
}
class MyCar extends Car<CarProps,CarState> {
state = {
moving: "yes",movingFast: "no"
};
render() {
return (
<div>
<div>movingFast : {this.state.movingFast}</div>
<div>tires : {this.props.tires}</div>
<div>color : {this.props.color}</div>
<div>moving : {this.state.moving}</div>
</div>
);
}
}
render(
<MyCar tires={3} color={"red"} />,document.getElementById("root")
);
如果我用某个函数替换构造函数,则存在其他或相同的问题:
abstract class Car<P,S> extends React.Component<AbCarProps & P,AbCarState & S> {
move = ()=>{
this.setState({moving:'yes'})
}
}
Argument of type '{ moving: "yes"; }' is not assignable to parameter of type '(AbCarState & S) | ((prevState: Readonly<AbCarState & S>,props: AbCarProps & P) => (AbCarState & S) | Pick<...>) | Pick<...>'.
Type '{ moving: "yes"; }' is not assignable to type 'Pick<AbCarState & S,"moving">'.
Types of property 'moving' are incompatible.
Type 'string' is not assignable to type 'string & S["moving"]'.
Type 'string' is not assignable to type 'S["moving"]'
所以我做错了什么。我该怎么做才能让它发挥作用? 谢谢
解决方法
你很近。只是忘记将 P
和 S
传递给组件以在抽象类中引用。
这是代码和框:
https://codesandbox.io/s/react-typescript-playground-forked-cm3oj?file=/src/index.tsx
abstract class Car<P,S> extends React.Component<
P & AbCarProps,// passing P to be part of props
S | AbCarState // passing S to be one of the states
> {
constructor(props: P & AbCarProps) {
super(props);
this.state = {
moving: "no"
};
console.log("Constructor");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。