【问题标题】:How to define defaultProps for a stateless react component in typescript?如何在打字稿中为无状态反应组件定义 defaultProps?
【发布时间】:2017-01-21 01:56:30
【问题描述】:

我想为我的纯函数组件定义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

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你可以像这样输入Page

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

    然后你可以写Page.defaultProps而不需要转换成anydefaultProps的类型将是PageProps)。

    【讨论】:

      【解决方案2】:

      通过使用 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;
      

      【讨论】:

        猜你喜欢
        • 2016-09-12
        • 2017-08-10
        • 2018-01-08
        • 2017-01-22
        • 1970-01-01
        • 2022-09-27
        • 2021-11-18
        • 1970-01-01
        • 2021-10-29
        相关资源
        最近更新 更多