问题描述
我有什么
import { NextPage } from 'next';
import React from 'react';
interface Props {
name: string;
gretting?: string; // Error: ESLint: propType "gretting" is not required,but has no corresponding defaultProps declaration.(react/require-default-props)
}
const Hello: React.FunctionComponent<Props> = ({ name,gretting = 'night' }: Props) =>
<p>Hi {name} Good {gretting}</p>;
const Home: NextPage = () => <Hello name="Jhon Doe" />;
export default Home;
问题
Eslint react插件抱怨此错误ESLint: propType "gretting" is not required,but has no corresponding defaultProps declaration.(react/require-default-props)
。
根据此answer方法,使用defaultProps
的默认参数值可以很好地解决问题,那么解决此问题的最佳方法是什么?使用Hello.defaultProps = {}
还是关闭规则react/require-default-props
?有更好的方法吗?。
解决方法
我遇到了这个问题并通过导出类型或接口来解决它,但我无法解释为什么这是问题的解决方案。
export interface Props {
name: string;
greeting?: string;
}
const Hello = ({name,greeting = 'Hi'}: Props): JSX.Element = {}
编辑:发现您需要 Typescript 3.0 根据此答案:https://stackoverflow.com/a/51486735/5059401
,我发现了功能组件的另一种解决方案-您可以只使用React.FC
,它为静态属性(例如defaultProps)提供类型检查和自动完成功能。
const Hello: React.FC<{name: string,gretting: string}> = ({ name,gretting = 'night' }) =>
在这种情况下,您根本不需要使用界面。但万一您出于某种原因想要
const Hello: React.FC<IProps> = ({ name,gretting = 'night' }) =>
===== UPDATE =====
另外:
"react/prop-types": "off" // Since we do not use prop-types
"react/require-default-props": "off" // Since we do not use prop-types
当传递的属性为null或未定义时使用defaultProp
interface Props {
name: string;
gretting?: string;// question mark means it could be undefined
}
在此界面中,您将名称声明为字符串,这意味着它不会为null或未定义,
因此您可以跳过defaultProp
但是gretting被声明为字符串或未定义,因此将其更改为未定义,因此有必要使用defaultProp
Hello.defaultProps = {
gretting: '',};