TypeScript写React组件默认属性问题
Author:zhoulujun Date:
通过组件的 defaultProps 属性可为其 Props 指定默认值。官方案例:https://reactjs.org/docs/typechecking-with-proptypes.html#default-prop-values
今天发现TS里面
import { ReactElement, Component } from 'react';
class Modal extends Component<ModalProps, ModalState> {}
ModalState.defaultProps={}
React.Component Property 'defaultProps' does not exist on type
因为加入 TypeScript React.Component 类型上并没有该属性。此时不支持直接通过类访问 defaultProps 来赋值以设置默认属性
起初没有找到办法,只有用高阶组件再传一遍值
const defaultProps={}
function withDefaultProps<P, DP extends Partial<P>> (
dp: DP,
component: React.ComponentType<P>
) {
component.defaultProps = dp
type RequiredProps = Omit<P, keyof DP>;
return (component as React.ComponentType<any>) as React.ComponentType<
RequiredProps & DP
>
}
withDefaultProps(defaultProps,Modal)
也可以写为:
class Foo extends Component<Props> {
static defaultProps: Partial<Props> = {
bar: false,
};
render() {
...
}
}
具体参看:https://stackoverflow.com/questions/57490998/property-defaultprops-does-not-exist-on-type
转载本站文章《TypeScript写React组件默认属性问题》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/jsBase/2020_1224_8745.html