如何在打字稿中为无状态反应组件定义 defaultProps? [英] How to define defaultProps for a stateless react component in typescript?
本文介绍了如何在打字稿中为无状态反应组件定义 defaultProps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的纯函数组件定义 defaultprops
但我收到一个类型错误:
导出接口 PageProps 扩展 React.HTMLProps{工具栏项目?:JSX.Element;标题?:字符串;}const Page = (props: PageProps) =>(<div className="row"><Paper className="col-xs-12 col-sm-offset-1 col-sm-10" zDepth={1}><应用栏标题={道具.标题}z深度={0}style={{ backgroundColor: "white" }}showMenuIconButton={false}iconElementRight={props.toolbarItem}/>{props.children}</纸>
);Page.defaultProps = {工具栏项目:空,};
我知道我可以写这个:
(Page as any).defaultProps = {工具栏项目:空,};
有没有更好的方法来添加defaultProps
?
解决方案
您可以像这样输入 Page
:
const 页面:StatelessComponent=(道具)=>(//...);
然后你就可以写Page.defaultProps
而无需转换为any
(defaultProps
的类型将是PageProps
代码>).
I want to define defaultprops
for my pure functional component but I get a type error:
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,
};
I know that I can write this:
(Page as any).defaultProps = {
toolbarItem: null,
};
Is there a better way to add defaultProps
?
解决方案
You can type Page
like this:
const Page: StatelessComponent<PageProps> = (props) => (
// ...
);
Then you can write Page.defaultProps
without needing to cast to any
(the type of defaultProps
will be PageProps
).
这篇关于如何在打字稿中为无状态反应组件定义 defaultProps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文