Eslint: 函数式组件中默认属性的问题(Typescript - React)

34

我的拥有

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)

根据这个答案,使用默认参数值的 defaultProps 方法是可行的,那么解决这个问题的最佳方法是什么?使用 Hello.defaultProps = {} 或关闭规则 react/require-default-props? 还有更好的方法吗?


Props被声明为nombre, saludo,但被解构为name, greeting。这段代码真的是你所拥有的吗?因为它不会起作用。 - Alex Wayne
@AlexWayne 对不起,那是我的错,我已经纠正了。 - Cristian Flórez
3个回答

34

我发现了另一个函数组件的解决方案 - 你可以使用React.FC,它为静态属性(例如defaultProps)提供类型检查和自动完成。

const Hello: React.FC<{name: string, gretting: string}> = ({ name, gretting = 'night' }) =>

在这种情况下,你根本不需要使用接口。但如果你出于某种原因想要使用:

const Hello: React.FC<IProps> = ({ name, gretting = 'night' }) =>

===== 更新 =====

此外:

"react/prop-types": "off" // 因为我们不使用 prop-types

"react/require-default-props": "off" // 因为我们不使用 prop-types


1
我无法重现这个问题,在我的情况下,eslint在界面上继续显示相同的错误... 我需要更多的上下文信息,你是否在某个地方使用了 Hello.defaultProps = {} 或者其他未在答案中提到的附加内容? - Cristian Flórez
不,我没有使用 defaultProps,而是将 FunctionalComponent 替换为 FC,并从括号中删除了接口类型。我还使用了非常严格的 eslint 配置,完全遵循 airbnb 规范。我在这里找到了这个解决方案:https://www.pluralsight.com/guides/defining-props-in-react-function-component-with-typescript - enk1
7
我已添加更新。对于React + TS组合,这个eslint规则毫无意义。 - enk1
有否对 React.FC 的任何评论?https://github.com/facebook/create-react-app/pull/8177 - franchb

14

我曾遇到此问题并通过导出类型或接口进行解决,尽管我无法解释为什么这是解决该问题的方法。

export interface Props {
  name: string;
  greeting?: string;
}

const Hello = ({name, greeting = 'Hi'}: Props): JSX.Element = {}

编辑:根据此答案,您需要Typescript 3.0:https://dev59.com/FVoU5IYBdhLWcg3wnX5O#51486735


我认为它解决了问题,因为你使用 greeting = 'Hi' 显式地设置了默认值。 - Petruza

3

defaultProp在传递的属性为null或undefined时使用

interface Props {
  name: string;
  gretting?: string;// question mark means it could be undefined
}

在这个接口中,你将名称声明为字符串,这意味着它不会是null或undefined,所以你可以跳过对其的defaultProp设置。 但是gretting声明为字符串或undefined,因此它可能为undefined,因此需要为它设置defaultProp。
Hello.defaultProps = {
  gretting: '',
};

编辑:根据这个答案,发现您需要使用Typescript 3.0:https://dev59.com/FVoU5IYBdhLWcg3wnX5O#51486735


每当我在props中使用?:时,是否应该通过defaultProps = {}显式声明它们的默认值?另外,属性的默认值在gretting ='night'中没有传递吗? - Cristian Flórez
是的,react/require-default-props 不会考虑你的参数默认值,它只检查 defaultProps。在这种情况下,你可以简单地禁用它。 - arslan2012
我不确定,我应该全局禁用规则还是仅针对此情况?因为每当我需要使用可选的 prop(?:) 时禁用规则非常低效...或者更好的方法是我应该始终设置 myComponent.defaultProps = {} 而不是参数默认值吗? - Cristian Flórez
defaultProps 用于 js。Typescript 有另一种声明 prop 类型的方式。 - akim lyubchenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接