React Material UI 和 React hook 形成清晰按钮动态组件

问题描述 投票:0回答:1

我想编写一个自定义 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}
    />
  );
}

enter image description here

reactjs material-ui
1个回答
0
投票

您的

...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}
    />
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.