Joe*_*ina 2 typescript reactjs
我正在创建一个扩展 React 组件的抽象类,我希望能够设置一些默认的道具,但也让扩展抽象类的组件提供自己的道具。
interface Props {
someProps: boolean
}
abstract class AbstractPureForm<P, S> extends React.Component<Props & P, S> {
...
}
Run Code Online (Sandbox Code Playgroud)
如何使用:
class Other extends AbstractPureForm<{ newProps: string}, {}> {
...
}
Run Code Online (Sandbox Code Playgroud)
现在这个设置给了我错误:
does not exist on type '(Props & P)["..."]'
Run Code Online (Sandbox Code Playgroud)
而不是Props & P(据我所知,无法将其指定为泛型类型参数),您的抽象类应该为其道具采用泛型值,类型为P extends Props:
export interface Props {
someProps: boolean;
}
export abstract class AbstractPureForm<P extends Props, S> extends React.Component<P, S>{
// ...
}
Run Code Online (Sandbox Code Playgroud)
Props接口提供 props您的具体子类 ,Other应该通过以下方式接受显式扩展抽象类Props接口的道具OtherProps extends Props:
interface OtherProps extends Props {
newProps: string;
}
class Other extends AbstractPureForm<OtherProps, {}> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
Props界面相交来提供道具通过创建类型OtherConcreteProps & Props(具体子类和抽象类的 props 的交集),您可以像最初一样使用交集类型:
interface OtherConcreteProps {
newProps: string;
}
export type OtherProps = OtherConcreteProps & Props;
class Other extends AbstractPureForm<OtherProps, {}> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2457 次 |
| 最近记录: |