TypeScript版本:
1.7.5
码
class Foo extends React.Component<any, any> {
// ... some class definitions
}
Foo.defaultProps = {
bar: 'baz'
}
预期行为:
没错
实际行为:
TS2339:类型“ typeof Foo”上不存在属性“ defaultProps”。
嗨,我想使用带有ES6类的typescript创建react
如果我可以像上面那样设置类属性而不是类主体,那将是很棒的。 似乎打字稿不支持它?
错误是默认情况下Foo
没有defaultProps
静态属性。 因此,您只需要告诉编译器您想要这样的属性。
class Foo extends React.Component<any, any> {
static defaultProps: any;
}
Foo.defaultProps = {
bar: 'baz'
}
通常,如果道具的类型P
而不是any
,则道具将为class Foo extends React.Component<P, ...
和static defaultProps: P;
您也可以使用模块合并来减少一些代码:
class Foo { ... }
namespace Foo {
export const defaultProps = {
...
}
}
非常感谢您的友好回答! :+1:
最有用的评论
错误是默认情况下
Foo
没有defaultProps
静态属性。 因此,您只需要告诉编译器您想要这样的属性。通常,如果道具的类型
P
而不是any
,则道具将为class Foo extends React.Component<P, ...
和static defaultProps: P;