【发布时间】:2021-08-04 02:42:58
【问题描述】:
我有一个组件已准备好接收名为 type 的参数,该参数可以是 email、mobileNumber、cep、password' 四个选项之一。如果 属性类型值 是 密码,则不应解析属性图标和 onPressIcon。我将这个道具输入如下:
type TextInputT = {
type: 'email' | 'mobileNumber' | 'cep' | 'password';
name: string;
label: string;
onPressIcon: () => void;
icon: string;
};
如果 textinput 的类型是密码,如何使道具 icon 和 onPressIcon 无效?
我已经试过了
type TextInput = {
type: 'password';
name: string;
label: string;
};
type CustomTextInput = {
type: 'email' | 'mobileNumber' | 'cep';
name: string;
label: string;
onPressIcon: () => void;
icon: string;
};
export type TextInputT = TextInput | CustomTextInput;
但在组件道具类型分配中抛出错误如下
EDIT1:我的 TextInput.tsx
const TextInput: React.FC<TextInputT> = ({
type,
name,
label,
onPressIcon,
icon,
}) => {
const inputValueRef = React.useRef(null);
const [isFocused, setIsFocused] = React.useState<boolean>(false);
const [valueShown, setValueShown] = React.useState<boolean>(false);
const [field, meta, helpers] = useField(name);
const hasError: boolean = meta.touched && typeof meta.error !== 'undefined';
const error: string = meta.touched && meta.error;
return (
<Container>
<Content
active={isFocused}
error={hasError}
disabled={false}
onPress={() => inputValueRef?.current?.focus()}
activeOpacity={1}>
{(isFocused || meta.touched) && (
<Label active={isFocused} error={hasError} disabled={false}>
{label}
</Label>
)}
<InputBox>
<InputValue
ref={inputValueRef}
secureTextEntry={type === 'password' && !valueShown}
onFocus={() => setIsFocused(true)}
placeholder={!isFocused ? label : ''}
value={getFormattedValue({
value: field.value,
mask: type,
})}
onChangeText={field.onChange(name)}
onBlur={() => [setIsFocused(false), helpers.setTouched(true)]}
/>
{type === 'password' && (
<IconBox onPress={() => setValueShown(!valueShown)}>
<IconDynamic
name={`${valueShown ? 'EyeClosed' : 'Eye'}`}
width={24}
height={24}
fill={colors.C.default}
/>
</IconBox>
)}
{icon && onPressIcon && (
<IconBox onPress={onPressIcon}>
<IconDynamic
name={icon}
width={24}
height={24}
fill={colors.C.default}
/>
</IconBox>
)}
</InputBox>
</Content>
{hasError && (
<ErrorBox>
<TextError>{error}</TextError>
</ErrorBox>
)}
</Container>
);
};
export default TextInput;
【问题讨论】:
-
Please replace or supplement images of code or errors with plain text versions. 另外,请考虑提供一个minimal reproducible example 来演示与独立 IDE 一起使用时的错误。我的建议看起来像this code,但如果没有用例示例,很难判断它是否有效,或者您是否会遇到其他问题。可重现的示例可帮助您更快地获得好的答案。祝你好运!
标签: typescript react-native react-typescript