Default property value in React component using TypeScript

前端 未结 7 1045
温柔的废话
温柔的废话 2020-11-28 01:51

I can\'t figure out how to set default property values for my components using Typescript.

This is the source code:

class PageState
{
}

export class         


        
7条回答
  •  一整个雨季
    2020-11-28 02:06

    For the functional component, I would rather keep the props argument, so here is my solution:

    interface Props {
      foo: string;
      bar?: number; 
    }
    
    // IMPORTANT!, defaultProps is of type {bar: number} rather than Partial!
    const defaultProps = {
      bar: 1
    }
    
    
    // externalProps is of type Props
    const FooComponent = exposedProps => {
      // props works like type Required now!
      const props = Object.assign(defaultProps, exposedProps);
    
      return ...
    }
    
    FooComponent.defaultProps = defaultProps;
    

提交回复
热议问题