与 TypeScript 反应 - 在无状态函数中定义 defaultProps [英] React with TypeScript - define defaultProps in stateless function

查看:39
本文介绍了与 TypeScript 反应 - 在无状态函数中定义 defaultProps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.

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

一切都很好,这段代码运行正常.但我的问题是:如何为 CenterBox 组件定义 defaultProps ?

Everything is great and this code is working correctly. But there's my question: how can I define defaultProps for CenterBox component?

正如 react 文档 中提到的:

(...) 它们是输入的纯函数变换,零样板.但是,您仍然可以指定 .propTypes 和.defaultProps 通过将它们设置为函数的属性,就像您可以将它们设置在 ES6 类上.(...)

(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class. (...)

应该很简单:

CenterBox.defaultProps = {
    minHeight: 250
}

但此代码生成 TSLint 错误:error TS2339: Property 'defaultProps' 在类型 '(props: CenterBoxProps) => 上不存在.元素'.

But this code generates TSLint error: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.

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

So again: how can I correctly define defaultProps in my above stack (React + TypeScript)?

推荐答案

经过 2 个小时的寻找解决方案... 它正在工作.

After 2 hours of looking for solution... it's working.

如果你想定义defaultProps,你的箭头函数应该是这样的:

If you want to define defaultProps, your arrow function should look like:

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

然后你可以定义如下道具:

Then you can define props like:

CenterBox.defaultProps = { someProp: true }

请注意,React.SFCReact.StatelessComponent 的别名.

Note that React.SFC is alias for React.StatelessComponent.

我希望这个问题(和答案)对某人有所帮助.确保您已安装最新的 React 类型.

I hope that this question (and answer) help somebody. Make sure that you have installed newest React typings.

这篇关于与 TypeScript 反应 - 在无状态函数中定义 defaultProps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆