我使用最新的typescript和reactjs版本,并且扩展类及其接口的扩展存在问题。
对于几个表单元素(都具有相同的验证方法),我创建了一个如下所示的BaseComponent:
/// <reference path="../typings/tsd.d.ts" />
import React = require('react');
interface P {
id: string
onChange: Function
error: string
}
interface S {
value: string
isValid: boolean
}
class BaseComponent extends React.Component<P, S> {
protected isValid(value) {
//do stuff
}
}
export default BaseComponent;
从BaseComponent扩展的Component:
/// <reference path="../typings/tsd.d.ts" />
import React = require('react');
import BaseComponent from './baseComponent';
interface P {
id: string
onChange: Function
error: string
required?: boolean
}
interface S {
value: string
isValid: boolean
somethingNew: string
}
class NameFieldContainer extends BaseComponent {
constructor(props: any) {
super(props);
this.state = {
value: '',
isValid: false,
somethingNew: 'Foo'
};
this.aMethod();
}
protected aMethod() {
this.setState({somethingNew: 'Bar'});
}
public render() {
const somethingNew = this.state.somethingNew;
return (
<div>{somethingNew}</div>
);
}
export default NameFieldContainer;
现在我的编译器(和IDE)显示了新的state.somethingNew和props.required属性的一些问题。我不知道如何扩展这个。如何向BaseComponent传授他必须使用NameFieldContainer中的接口?
答案 0 :(得分:2)
您可以使用Intersection Type扩展现有的道具和状态界面。您的BaseContainer
看起来像这样
class BaseContainer<PP, SS> extends React.Component<P & PP, S & SS> {
}
以及您将使用
的具体实现interface PExtended {
id: string
onChange: Function
error: string
required?: boolean
}
interface SExtended {
value: string
isValid: boolean
somethingNew: string
}
class NameFieldContainer extends BaseContainer<PExtended, SExtended> {...}
如果州字段不是可选的(通过将其声明为value?:string
),您还必须记住,您必须在setState({})
中设置它们。