小编典典

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

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,
};

我知道我可以这样写:

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

有没有更好的添加方法defaultProps


阅读 248

收藏
2020-07-22

共1个答案

小编典典

您可以这样输入Page

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

然后,你可以写Page.defaultProps,而无需强制转换any的类型(defaultPropsPageProps)。

2020-07-22