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

后端 未结 4 828
清歌不尽
清歌不尽 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:31

    Here's a similar question with an answer: React with TypeScript - define defaultProps in stateless function

    import React, { Component } from 'react';
    import { Text } from 'react-native';
    
    interface TestProps {
        title?: string,
        name?: string
    }
    
    const defaultProps: TestProps = {
        title: 'Mr',
        name: 'McGee'
    }
    
    const Test: React.SFC = (props) => (
        
            {props.title} {props.name}
        
    );
    
    Test.defaultProps = defaultProps;
    
    export default Test;
    

提交回复
热议问题