Formik 验证不适用于 Material UI 自动完成功能

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

我想在用户清除选择时显示验证错误。

沙箱链接是https://codesandbox.io/p/sandbox/formik-autocomplete-yh3sl7?file=%2Fsrc%2FApp.tsx%3A1%2C1-84%2C1

  • 当表单初始加载时使用默认值。清除数值 不触发验证。

  • 刷新页面。单击提交。清除默认值,表格 验证触发器

  • 刷新页面。单击提交。清除默认值,表格 验证触发器。再次点击提交,然后清除 值不会触发验证。

import "./styles.css";
import { object, string } from "yup";
import { useFormik } from "formik";
import { useState } from "react";
import { Autocomplete, Box, TextField } from "@mui/material";

export default function App() {
  const parentCategory = [
    {
      id: "983868dc-106d-446b-822c-ff03e62099c6",
      name: "Electronics",
    },
    {
      id: "7c7ae7a1-bb3b-4c9d-8da2-91c2bf063875",
      name: "q",
    },
    {
      id: "4066deae-7144-40f1-99ab-cc9cf862eb8a",
      name: "Root",
    },
    {
      id: "28c9bd93-9f22-4753-8d63-3dcc4839eb07",
      name: "s",
    },
    {
      id: "6c4245e1-5cc1-4b07-b718-e47a2e0f33ea",
      name: "Television",
    },
  ];
  let categorySchema = object({
    parentId: string().required("Parent category is required.").nullable(),
  });

  const [formData, setFormData] = useState({
    name: "",
    parentId: "4066deae-7144-40f1-99ab-cc9cf862eb8a",
  });

  const initialCategoryValue = {
    name: "Root",
    id: "4066deae-7144-40f1-99ab-cc9cf862eb8a",
  };

  const formik = useFormik({
    initialValues: formData,
    validationSchema: categorySchema,
    onSubmit: (values) => {
      debugger;
    },
  });

  return (
    <div className="App">
      <form onSubmit={formik.handleSubmit}>
        <Autocomplete
          id="ddParentCategory"
          size="small"
          sx={{ width: 300 }}
          getOptionLabel={(option) => option.name}
          getOptionKey={(option) => option.id}
          options={parentCategory}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Parent Category"
              name="parentId"
              error={formik.touched.parentId && Boolean(formik.errors.parentId)}
              helperText={formik.touched.parentId && formik.errors.parentId}
            />
          )}
          isOptionEqualToValue={(option, value) => option.id === value.id}
          defaultValue={initialCategoryValue}
          onChange={(e, value, reason) => {
            formik.setFieldValue("parentId", value?.id);
            console.log(value?.id);
            console.log(formik.getFieldMeta("parentId"));
          }}
        />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}
reactjs material-ui autocomplete formik formik-material-ui
1个回答
0
投票

Mui 的 TextField 中的错误字段需要布尔值!试试这个,应该有效:

    <TextField
      {...params}
      label="Parent Category"
      name="parentId"
      error={Boolean(formik.errors.parentId)}
      helperText={formik.errors.parentId}
    />
© www.soinside.com 2019 - 2024. All rights reserved.