请考虑以下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
中对其进行销毁。但我也需要name
和icon
用于其他目的,所以我创建了一个扩展TextInputProps
的接口,在那里指定了这些属性,并将InputProps
传递给React.FC
。
现在我得到了'name' is missing in props validation - eslintreact/prop-types
(与"图标"相同(,但当我试图获得TextInputProps
中指定的任何属性时,都没有发生这种情况。
编写const Input: React.FC<InputProps> = ({ name, icon, ...props }: InputProps) => (/*...*/);
使linter不再抱怨,但我仍然不明白为什么使用type参数没有。有人能向我澄清一下吗?我是不是搞错了什么概念,还是只是门楣有问题?
附言:我是在扩展名为ESLint的VS代码上写这篇文章的。
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 */
`;
从外观上看,eslint-plugin-react/prop-types
不处理仅在变量类型注释中声明道具类型的情况。
他们唯一使用这种语法的测试也显式地键入props
arg,这可能是他们没有处理这种情况的原因。
https://github.com/yannickcr/eslint-plugin-react/blob/72275716be7fb468fc9a2115603d9c1b656aa0da/tests/lib/rules/prop-types.js#L2578-L2599
考虑在他们的回购中提出一个错误https://github.com/yannickcr/eslint-plugin-react
eslint-plugin-react@^7.25.0
已解决此问题
所以更新后:
const Component: React.FC<Props> = (props: Props) => {}
可以简化为
const Component: React.FC<Props> = (props) => {}