How to specify (optional) default props with TypeScript for stateless, functional React components?

后端 未结 4 830
清歌不尽
清歌不尽 2021-01-31 07:42

I\'m trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I\'m stum

4条回答
  •  孤街浪徒
    2021-01-31 08:39

    Here's how I like to do it:

    type TestProps = { foo: Foo } & DefaultProps
    type DefaultProps = Partial
    const defaultProps = {
      title: 'Mr',
      name: 'McGee'
    }
    
    const Test = (props: Props) => {
      props = {...defaultProps, ...props}
      return (
        
          {props.title} {props.name}
        
      )
    }
    
    export default Test
    

提交回复
热议问题