为可选PropType设置默认值后仍遇ESLint报错的问题咨询
解决React+TypeScript中ESLint可选Props缺省值报错问题
初始代码
type TopBarProps = { problemPage?: boolean; // 原标记存在问题 }; function TopBar({ problemPage }: TopBarProps) { ... }
尝试修改后的代码
参考方案调整后代码如下:
type TopBarProps = { problemPage?: boolean; // 原标记问题处 }; function TopBar({ problemPage = false }: TopBarProps) { ... }
仍触发的ESLint报错(中文翻译)
propType "problemPage" 并非必填项,但未声明对应的defaultProps。eslint(react/require-default-props)
问题原因与解决办法
ESLint的react/require-default-props规则强制要求:所有非必填的Props必须显式声明defaultProps,即便你已经在函数参数中设置了默认值——该规则不认可参数默认值的写法。
规范修复代码
显式添加defaultProps即可解决报错:
type TopBarProps = { problemPage?: boolean; }; function TopBar({ problemPage }: TopBarProps) { ... } TopBar.defaultProps = { problemPage: false };
优化写法(TypeScript特性适配)
在TypeScript中,添加defaultProps后可以去掉类型定义里的可选标记?,TypeScript会自动推断该Props为可选且带有默认值:
type TopBarProps = { problemPage: boolean; }; function TopBar({ problemPage }: TopBarProps) { ... } TopBar.defaultProps = { problemPage: false };
内容的提问来源于stack exchange,提问作者Yukinosuke Takada
相关产品推荐
相关产品推荐

