Typescript React直通道具/状态界面

时间:2019-05-13 14:43:55

标签: reactjs typescript

当我要在组件内执行其余操作时,我使用派生组件来简化对数据检索/成功/失败的管理。

BaseRestComponent.tsx

interface IDictionary<T> {
    [index: string]: T;
}
interface IStateBase {
    validationStatus: number;
    validationMessage: string;
    [others: string]: any;
}
interface IEvent {
    target: {
        id: string
        value: string
    }
}
class BaseRestComponent<prop, state extends IStateBase> extends Component<prop, state> {
    restService = new RestService();
    authService = new AuthService();
    dataService = new DataService();
    constructor(props: any) {
        super(props);

        this.state = {
            validationStatus: 1 //err
            , validationMessage: ""
        }
    }

    mapToOptions(lookupValues: string[]) {
        return lookupValues.map((lookupName, i) => 
        {
            return <option key={i} value={lookupName}>{lookupName}</option>;
        });
    }
    mapLookupToOptions(lookupValues: IDictionary<string[]>, dropdownLookup: string) {
        return this.mapToOptions(lookupValues[dropdownLookup]);
    }

    validationClass() {
        if(this.state.validationStatus === 0) {
            return "validation-status error";
        }
        if(this.state.validationStatus === 1) {
            return "validation-status success";
        }
    }

    handleChange = (event: IEvent) => {
        // console.log(event);
        this.setState({
            [event.target.id]:event.target.value
        } as any);
    }
    handleDateChange(date: number, id: string) {
        this.setState({
            [id]: date
        } as any);
    }
}

但是,打字稿编译器不喜欢我试图为上面的状态对象声明一组默认属性。对于“ validationStatus”属性,我得到了错误:Property 'validationStatus' does not exist on type 'Readonly<state>'.ts(2339)

我在这里做错什么了吗?我知道我最终将不得不将interface移出,或者将exportBaseRestComponent移到extend并移入其他文件中。

0 个答案:

没有答案