小编典典

使用TypeScript进行反应-在无状态函数中定义defaultProps

reactjs

我将React与TypeScript一起使用,并且创建了无状态函数。为了便于阅读,我从示例中删除了无用的代码。

interface CenterBoxProps extends React.Props<CenterBoxProps> {
    minHeight?: number;
}

export const CenterBox = (props: CenterBoxProps) => {
    const minHeight = props.minHeight || 250;
    const style = {
        minHeight: minHeight
    };
    return <div style={style}>Example div</div>;
};

一切都很好,此代码可以正常工作。但有我的问题:我怎么可以定义defaultPropsCenterBox组件?

正如在react docs中提到的那样:

(…)它们是输入的纯函数转换,带有零样板。但是,仍然可以通过将.propTypes和 .defaultProps 设置为函数的属性来指定
它们,就像在ES6类上进行设置一样。(…)

它应该很容易,因为:

CenterBox.defaultProps = {
    minHeight: 250
}

但是这段代码会产生TSLint错误: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

再说一遍:如何正确定义defaultProps上述堆栈(React + TypeScript)?


阅读 432

收藏
2020-07-22

共1个答案

小编典典

寻找解决方案2个小时后, 它开始起作用

如果要定义defaultProps,则箭头函数应如下所示:

export const CenterBox: React.SFC<CenterBoxProps> = props => {
    (...)
};

然后,您可以定义道具,例如:

CenterBox.defaultProps = { someProp: true }

请注意,这React.SFC是的别名React.StatelessComponent

我希望这个问题(和答案)能帮助到别人。确保您已经安装了最新的React类型。

2020-07-22