oop – 在TypeScript中扩展React组件

前端之家收集整理的这篇文章主要介绍了oop – 在TypeScript中扩展React组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用React.js与TypeScript.有没有办法创建继承自其他组件的React组件,但是还有一些额外的道具/状态?

我想要实现的是这样的:

interface BaseStates {
    a: number;
}

class GenericBase<S extends BaseStates> extends React.Component<void,S> {
    protected getBaseInitialState(): BaseStates {
        return { a: 3 };
    }
}

class Base extends GenericBase<BaseStates> {
    getInitialState(): BaseStates {
        return super.getBaseInitialState();
    }
}

interface DerivedStates extends BaseStates {
    b: number;
}

class Derived extends GenericBase<DerivedStates> {
    getInitialState(): DerivedStates {
        var initialStates = super.getBaseInitialState() as DerivedStates; // unsafe??
        initialStates.b = 4;
        return initialStates
    }
}

但是,如果我在Derived中调用this.setState,则会失败,我得到一个TypeScript错误(DerivedStates类型的参数不能分配给类型S).我想这不是一个特定于TypeScript的东西,而是将继承与泛型(?)进行混合的一般限制.有没有类型安全的解决方法

UPDATE

解决解决方案(根据David Sherret的答案):

interface BaseStates {
    a: number;
}

class GenericBase<S extends BaseStates> extends React.Component<void,S> {
    constructor() {
        super();
        this.state = this.getInitialState();
    }

    getInitialState(): S {
        return { a: 3 } as S;
    }

    update() {
        this.setState({ a: 7 } as S);
    }
}

interface DerivedStates extends BaseStates {
    b: number;
}

class Derived extends GenericBase<DerivedStates> {
    getInitialState(): DerivedStates {
        var initialStates = super.getInitialState();
        initialStates.b = 4;
        return initialStates;
    }

    update() {
        this.setState({ a: 7,b: 4 });
    }
}
您可以通过使用类型断言在派生中一次只设置状态的几个属性
this.setState({ b: 4 } as DerivedStates); // do this
this.setState({ a: 7 } as DerivedStates); // or this
this.setState({ a: 7,b: 4 });            // or this

顺便说一句,没有必要为getInitialState有不同的名字…你可以做:

class GenericBase<S extends BaseStates> extends React.Component<void,S> {
    constructor() {
        super();        
        this.state = this.getInitialState();
    }

    protected getInitialState() {
        return { a: 3 } as BaseStates as S;
    }
}

class Derived extends GenericBase<DerivedStates> {
    getInitialState() {
        var initialStates = super.getInitialState();
        initialStates.b = 4;
        return initialStates;
    }
}
原文链接:https://www.f2er.com/react/301199.html

猜你在找的React相关文章