我想编写一个自定义 React TextField 组件,并且想向此自定义组件添加一个清除按钮。我添加了该按钮,但其功能不起作用。下面我分享一下自定义组件的调用和内容。
const { handleSubmit, control, formState } = useForm<SignInModel>({
resolver: zodResolver(signinSchema),
defaultValues: signinDefaultValue,
});
<Controller
name="email"
control={control}
render={({ field: { ref, ...field } }) => (
<ValidationTextField
label={t("auth.email")}
type="email"
autoComplete="email"
helperText={!!errors.email && (isDirty || isSubmitted) ? String(errors.email.message) : null}
{...field}
/>
)}
/>
interface ValidationTextFieldProps
extends Omit<FilledTextFieldProps, "variant"> {}
export function ValidationTextField(props: ValidationTextFieldProps) {
const [value, setValue] = useState("");
return (
<TextField
required
margin="normal"
fullWidth
helperText={props.helperText}
error={!!props.helperText}
onChange={(e) => setValue(e.target.value)}
value={value}
FormHelperTextProps={{
style: { width: "fit-content", marginRight: 0 },
}}
InputProps={{
endAdornment: !!props.value && (
<IconButton
aria-label="toggle password visibility"
onClick={() =>{ setValue("") }}
>
<CancelRoundedIcon />
</IconButton>
),
}}
{...props}
/>
);
}
您的
...field
和 ...props
包含 value
和 onChange
,因此组件中根本不应该有 value
状态。
它应该看起来像这样:
export function ValidationTextField(props: ValidationTextFieldProps) {
return (
<TextField
required
margin="normal"
fullWidth
helperText={props.helperText}
error={!!props.helperText}
FormHelperTextProps={{
style: { width: "fit-content", marginRight: 0 },
}}
InputProps={{
endAdornment: !!props.value && (
<IconButton
aria-label="toggle password visibility"
onClick={() =>{ props.onChange("") }}
>
<CancelRoundedIcon />
</IconButton>
),
}}
{...props}
/>
);
}