我不知道如何使用Typescript为我的组件设置默认属性值。
这是源代码:
class PageState
{
}
export class PageProps
{
foo: string = "bar";
}
export class PageComponent extends React.Component<PageProps, PageState>
{
public render(): JSX.Element
{
return (
<span>Hello, world</span>
);
}
}
当我尝试像这样使用组件时:
ReactDOM.render(<PageComponent />, document.getElementById("page"));
我得到一个错误,说属性foo丢失了。我想使用默认值。我还尝试使用静态defaultProps =…但它并没有像我怀疑的那样起作用。
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
如何使用默认属性值?我的公司使用的许多JS组件都依赖于它们,不使用它们是不可取的。
来自@pamelus对公认答案的评论:
您要么必须使所有接口属性都是可选的(糟糕),要么
还为所有必选字段指定默认值(不需要)
boilerplate)或避免在defaultProps上指定类型。
实际上你可以使用Typescript的接口继承。结果代码只是稍微啰嗦一点。
interface OptionalGoogleAdsProps {
format?: string;
className?: string;
style?: any;
scriptSrc?: string
}
interface GoogleAdsProps extends OptionalGoogleAdsProps {
client: string;
slot: string;
}
/**
* Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
*/
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
public static defaultProps: OptionalGoogleAdsProps = {
format: "auto",
style: { display: 'block' },
scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
};
来自@pamelus对公认答案的评论:
您要么必须使所有接口属性都是可选的(糟糕),要么
还为所有必选字段指定默认值(不需要)
boilerplate)或避免在defaultProps上指定类型。
实际上你可以使用Typescript的接口继承。结果代码只是稍微啰嗦一点。
interface OptionalGoogleAdsProps {
format?: string;
className?: string;
style?: any;
scriptSrc?: string
}
interface GoogleAdsProps extends OptionalGoogleAdsProps {
client: string;
slot: string;
}
/**
* Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
*/
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
public static defaultProps: OptionalGoogleAdsProps = {
format: "auto",
style: { display: 'block' },
scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
};