我有一个如下所示的自定义组件:
import Icon from 'react-native-vector-icons/FontAwesome';
export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
handleChange,
handleBlur,
fieldType,
placeholderText,
value,
hidePassword,
hidePasswordIcon,
togglePassword,
icon,
}) => {
return (
<Item>
<Icon name={icon} />
<Input
autoFocus={true}
autoCapitalize="none"
placeholder={placeholderText}
keyboardType="default"
onChangeText={handleChange(fieldType)}
onBlur={handleBlur(fieldType)}
value={value}
secureTextEntry={hidePassword}
/>
{togglePassword ? (
<Icon
name={hidePasswordIcon}
onPress={togglePassword}
style={commonStyles.iconStyle}
size={moderateScale(20)}
color="green"
/>
) : null}
</Item>
);
};
<FieldInput style={styles.fieldInput}
handleChange={handleChange}
handleBlur={handleBlur}
value={values.phoneNumber}
fieldType="phoneNumber"
icon="phone"
placeholderText="49152901820"
/>
虽然它运行正常,但我不断收到来自
name
的 Icon
上的重载错误。
No overload matches this call.
Overload 1 of 2, '(props: Readonly<IconProps>): Icon', gave the following error.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Overload 2 of 2, '(props: IconProps, context?: any): Icon', gave the following error.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2769)
Icon.d.ts(26, 3): The expected type comes from property 'name' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Icon> & Readonly<IconProps> & Readonly<{ children?: ReactNode; }>'
我该如何解决这个问题?我找不到列表/文档来检查字体真棒图标的可接受属性。
您的 Icon 组件的
icon
属性似乎是可选的。您可以确保 prop 值永远不会未定义,或者,如果您确定在渲染此组件之前始终定义 prop 值,则可以将 prop 转换为字符串,如下所示:
<Icon name={icon as string} />
为了更好地处理 prop 未定义的情况,您可以使用条件渲染:
{icon !== undefined && <Icon name={icon} />}