[英]React with TypeScript - define defaultProps in stateless function
[英]How to define defaultProps for a stateless react component in typescript?
我想為我的純功能組件定義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
而不必Page.defaultProps
轉換為any
類型( defaultProps
的類型為PageProps
)。
通過使用Javascript自己的默認函數參數,這非常簡單,並且使用Typescript泛型,您將在組件內部和組件使用者外部獲得強大的正確類型信息。
import React, { FC } from "react";
interface MyComponentProps {
name?: string;
}
const MyComponent: FC<MyComponentProps> = ({ name = "Someone" }) => {
// note that Typescript knows that the property will never
// be `undefined` inside this function
return <div>Hello {name}</div>;
}
export default MyComponent;
您可以像這樣使用組件:
import React, { FC } from "react":
import MyComponent from "./MyComponent";
const ParentComponent: FC = () => {
// Typescript knows that you name is optional
// and will not complain if you don't provide it
return (
<div>
<MyComponent />
<MyComponent name="Jane" />
</div>
);
}
export default ParentComponent;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.