我有一个像这样的 Typescript React 类组件:
import React, { Component } from 'react';
interface Props {
bar?: boolean;
}
const defaultProps: Partial<Props> = {
bar: false,
};
class Foo extends Component<Props> {
render() {
...
}
}
Foo.defaultProps = defaultProps;
export default Foo;
这里我得到以下类型错误:
Property 'defaultProps' does not exist on type 'typeof Foo'.
我看到了 2 个解决方案来解决这个问题。一种是像这样在类上声明类型:
class Foo extends Component<Props> {
static defaultProps: Partial<Props>;
render() {
...
}
}
另一种是完全像这样在类中声明 defaultProps:
class Foo extends Component<Props> {
static defaultProps: Partial<Props> = {
bar: false,
};
render() {
...
}
}
我使用的是 eslint-config-airbnb 18.0.1 和 eslint 6.1.0,所以这两种解决方案都会抛出这个 eslint 错误:
'defaultProps' 应该在类主体之外声明(react/static-property-placement)
有没有办法在类外声明 defaultProps 而不会抛出类型错误?
最佳答案
TS 文档说静态 defaultProps 是 the way to go .
在 TS 之上添加 eslint 似乎很奇怪,我相信 airbnb 配置是针对 javascript,而不是 TypeScript。
关于javascript - 类型上不存在属性 'defaultProps',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57490998/