我想在用户清除 Select 时显示验证错误.

enter image description here

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

  • 当表单初始加载默认值时.清除该值 不会触发验证.

  • 刷新页面.点击提交.清除缺省值Form 验证触发器

  • 刷新页面.点击提交.清除缺省值Form 验证触发器. Again click on submit and after that clearing the value does not trigger the validation.

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>
  );
}

推荐答案

看看这个,从你的代码编辑的代码.

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, helpers) => {
      console.log(values);
      helpers.resetForm();
    },
  });

  return (
    <div className="App">
      <form
        onSubmit={(e) => {
          console.log(Boolean(formik.errors.parentId));
          console.log(formik.errors.parentId);

          formik.handleSubmit(e);
        }}
      >
        <Autocomplete
          id="ddParentCategory"
          size="small"
          sx={{ width: 300 }}
          getOptionLabel={(option) => option.name}
          getOptionKey={(option) => option.id}
          options={parentCategory}
          renderInput={(params) => (
            <TextField
              {...params}
              onBlur={formik.handleBlur}
              label="Parent Category"
              name="parentId"
              error={Boolean(formik.errors.parentId)}
              helperText={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相关问答推荐

更新数据时有关CQR和更新UI的问题

为什么我的标签在Redux API中不能正常工作?

如何使用next.js以DOM为目标在映射中使用Ref

在Reaction中单击时,按钮未按预期工作

根据另一个Select中的选定值更改Select中的值

有没有办法将在服务器端全局获取的一些数据传递到Next&>13应用程序目录中的客户端组件?

为什么我得不到我想要的数据?

useState导致对函数的无休止调用

React组件未出现

获取类别和页面的参数

我发送的 prop 的值不会改变.如果成功登录,导航栏中的 prop 必须为 true.我从后端得到 200 ok

如何隐藏移动导航栏后面的向下滚动图标和文本?

无法使用 MongoDB Atlas 和 Next.js 删除正确的帖子

React 测试库包装器组件

运行 npm run build 出现问题

为什么 createSlice 中的 reducer 不能以不同的方式改变状态?

SonarCloud 代码覆盖率不适用于 Github Action

getAttribute 函数并不总是检索属性值

链接的音译 Gatsby JS

我可以在类组件中使用 useState 挂钩吗?