如何为打字稿中的无状态反应组件定义defaultProps?

问题描述:

我想定义defaultprops我的纯功能性成分,但我得到一个错误类型:如何为打字稿中的无状态反应组件定义defaultProps?

export interface PageProps extends React.HTMLProps<HTMLDivElement> { 
    toolbarItem?: JSX.Element; 
    title?: string; 
} 

const Page = (props: PageProps) => (
    <div className="row"> 
     <Paper className="col-xs-12 col-sm-offset-1 col-sm-10" zDepth={1}> 
      <AppBar 
       title={props.title} 
       zDepth={0} 
       style={{ backgroundColor: "white" }} 
       showMenuIconButton={false} 
       iconElementRight={props.toolbarItem} 
      /> 
      {props.children} 
     </Paper> 
    </div> 
); 

Page.defaultProps = { 
    toolbarItem: null, 
}; 

我知道我可以这样写:

(Page as any).defaultProps = { 
    toolbarItem: null, 
}; 

有没有更好的方式来增加defaultProps

你可以喜欢这类型Page

const Page: StatelessComponent<PageProps> = (props) => (
    // ... 
); 

然后,你可以写Page.defaultProps无需转换为any(的defaultProps的类型将是PageProps)。