2

请考虑以下 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。但我也需要nameandicon用于其他目的,所以我创建了一个扩展接口TextInputProps,在那里指定了这些属性,然后传递InputPropsReact.FC

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

写作const Input: React.FC<InputProps> = ({ name, icon, ...props }: InputProps) => (/*...*/);使 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 */
`;
4

1 回答 1

1

从外观eslint-plugin-react/prop-types上看,仅在变量类型注释中声明道具类型时不处理。

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

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

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

于 2020-07-31T00:02:06.067 回答