【问题标题】:Why, even after specifying a type parameter for a React component, the linter still complains about '<property>' missing in props validation?为什么即使在为 React 组件指定了类型参数之后,linter 仍然会抱怨 props 验证中缺少 '<property>'?
【发布时间】:2020-07-31 08:02:06
【问题描述】:

请考虑以下 TypeScript (.tsx) 代码:

import React from 'react';
import { TextInputProps } from 'react-native';
import { Container, TextInput, Icon } from './styles';

interface InputProps extends TextInputProps {
  name: string;
  icon: string;
}

const Input: React.FC<InputProps> = ({ name, icon, ...props }) => (
  <Container>
    <Icon name={icon} size={20} color="#666360" />

    <TextInput
      keyboardAppearance="dark"
      placeholderTextColor="#666360"
      {...props}
    />
  </Container>
);

export default Input;

通过将TextInputProps 作为类型参数传递给React.FC,我可以访问TextInput 属性,我将在...props 中对其进行解构。但是我还需要nameicon 用于其他目的,所以我创建了一个扩展TextInputProps 的接口,在那里指定了这些属性,并将InputProps 传递给React.FC

现在我得到'name' is missing in props validation - eslintreact/prop-types('icon' 相同),但是当我尝试获取TextInputProps 中指定的任何属性时,这并没有发生。

const Input: React.FC&lt;InputProps&gt; = ({ name, icon, ...props }: InputProps) =&gt; (/*...*/); 使 linter 停止抱怨,但我仍然不明白为什么使用 type 参数不会。有人可以向我澄清这一点吗?我是不是搞错了一些概念,还是只是 linter 的问题?

PS:我是在带有 ESLint 扩展的 VS Code 上写这篇文章的。

PS2:这是styles.ts 中的代码,如果有帮助的话:

import styled from 'styled-components/native';
import FeatherIcon from 'react-native-vector-icons/Feather';

export const Container = styled.View`
  /* Some CSS */
`;

export const TextInput = styled.TextInput`
  /* More CSS */
`;

export const Icon = styled(FeatherIcon)`
  /* ... and CSS */
`;

【问题讨论】:

    标签: typescript react-native type-parameter typescript-eslint


    【解决方案1】:

    从外观上看,eslint-plugin-react/prop-types 不处理 prop 类型仅在变量类型注解中声明的情况。

    他们唯一使用此语法的测试也显式键入了props arg,这可能是他们没有处理这种情况的原因。

    https://github.com/yannickcr/eslint-plugin-react/blob/72275716be7fb468fc9a2115603d9c1b656aa0da/tests/lib/rules/prop-types.js#L2578-L2599

    考虑在他们的 repo https://github.com/yannickcr/eslint-plugin-react 中提出一个错误

    【讨论】:

    • 那么这只是 eslint 的问题吗?不是打字稿代码本身。
    • 正确 - 当 VSCode 显示错误时,它会包含错误代码。这将帮助您弄清楚它的来源。在此示例中,错误代码应为 eslint(react/prop-types)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多