Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reactjs - 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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can type Page like this:

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

Then you can write Page.defaultProps without needing to cast to any (the type of defaultProps will be PageProps).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...