Extending React components in TypeScript

后端 未结 2 1534
离开以前
离开以前 2020-12-28 15:54

I\'m using React.js with TypeScript. Is there any way to create React components that inherit from other components but have some additional props/states?

What I\'m

相关标签:
2条回答
  • 2020-12-28 16:23
    import { Component } from 'react'
    
    
    abstract class TestComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> {
      abstract test(): string
    }
    
    
    type Props = {
      first: string,
      last: string,
    }
    
    type State = {
      fullName: string,
    }
    
    class MyTest extends TestComponent<Props, State> {
      constructor(props: Props) {
        super(props)
        this.state = {
          fullName: `${props.first} ${props.last}`
        }
      }
    
      test() {
        const { fullName } = this.state
        return fullName
      }
    }
    
    
    0 讨论(0)
  • 2020-12-28 16:30

    You can set only a few properties of the state at once in Derived by using a type assertion:

    this.setState({ b: 4 } as DerivedStates); // do this
    this.setState({ a: 7 } as DerivedStates); // or this
    this.setState({ a: 7, b: 4 });            // or this
    

    By the way, no need to have different names for getInitialState... you could just do:

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题