簡體   English   中英

如何為打字稿中的無狀態反應組件定義defaultProps?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM