如何在typescript中为无状态反应组件定义defaultProps?

ali*_*ari 5 typescript reactjs

我想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,
};
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样写:

(Page as any).defaultProps = {
    toolbarItem: null,
};
Run Code Online (Sandbox Code Playgroud)

有没有更好的添加方式defaultProps

Tom*_*ech 8

你可以这样输入Page:

const Page: StatelessComponent<PageProps> = (props) => (
    // ...
);
Run Code Online (Sandbox Code Playgroud)

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