简体   繁体   English

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

[英]How to define defaultProps for a stateless react component in typescript?

I want to define defaultprops for my pure functional component but I get a type error: 我想为我的纯功能组件定义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,
};

I know that I can write this: 我知道我可以这样写:

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

Is there a better way to add defaultProps ? 有没有更好的方法来添加defaultProps

You can type Page like this: 您可以这样输入Page

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

Then you can write Page.defaultProps without needing to cast to any (the type of defaultProps will be PageProps ). 然后,您可以编写Page.defaultProps而不必Page.defaultProps转换为any类型( defaultProps的类型为PageProps )。

This is fairly straightforward by using Javascript's own default function parameters, and with Typescript generics you will get strong correct type information both inside the component and in the outside world of component consumers. 通过使用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;

And you can consume the component like so: 您可以像这样使用组件:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM