我想为我的纯功能组件定义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
?
答案 0 :(得分:8)
您可以像这样输入Page
:
const Page: StatelessComponent<PageProps> = (props) => (
// ...
);
然后你可以写Page.defaultProps
而不需要转换为any
(defaultProps
的类型将是PageProps
)。
答案 1 :(得分:1)
通过使用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;