简体   繁体   English

使用 Formik 响应动态输入

[英]React Dynamic inputs with Formik

I am trying to dynamically remove an input field after a button is pressed and also remove the key with its value from Formik.我试图在按下按钮后动态删除输入字段,并从 Formik 中删除键及其值。 I am using the useFormik hook for implementation.我正在使用 useFormik 钩子来实现。 The problem is that when I press the button to remove the input field, it is removed but the key and value stay in useFormik.问题是当我按下按钮删除输入字段时,它被删除但键和值保留在 useFormik 中。 When I press the button again, another input field is removed and the previous key and value is removed from useFormik.当我再次按下按钮时,另一个输入字段被删除,并且先前的键和值从 useFormik 中删除。 Removing values from useFormik is one step behind.从 useFormik 中删除值落后了一步。 How can I change it so it removes the key and value at the same time as the input field?我如何更改它以便它在输入字段的同时删除键和值?

Here are initial values for Formik.以下是 Formik 的初始值。

const formik = useFormik({
    initialValues: {
      Produkt1:
        "",
      Produkt2:
        "",
    },
    validationSchema: frontProductUrls(),
    enableReinitialize: true,
    onSubmit: (values) => {
      console.log(values);
    },
    setFieldValue: () => {
      delete fields.length - 1;
    },
  });

This array i use to dynamicly add remove and render input fields.这个数组我用来动态添加删除和呈现输入字段。

const [fields, setFields] = useState([
    { name: "Produkt1", label: "Produkt 1" },
    { name: "Produkt2", label: "Produkt 2" },
  ]);

Here is function to remove last input filed in array and also remove key and value from useFormik.这里是 function 删除数组中的最后一个输入,并从 useFormik 中删除键和值。

const removeField = (e) => {
    formik.setFieldValue(`Produkt${fields.length + 1}`, undefined, false);

    let updatedFields = [...fields];
    updatedFields.splice(fields.length - 1, 1);
    setFields(() => updatedFields);
  };

This function is used to add new input field.这个 function 用于添加新的输入字段。 This work fine it add new input and also it add new key in useFormik.这项工作很好,它添加了新的输入,并且还在 useFormik 中添加了新的密钥。

const addField = () => {
    if (fields.length > 3) return;

    const newProduct = `Produkt${fields.length + 1}`;
    formik.setFieldValue(newProduct, "");
    setFields([
      ...fields,
      {
        name: newProduct,
        label: newProduct,
      },
    ]);
  };

Here is code where are fields rendered.这是呈现字段的代码。

{fields.map((field, index) => {
          return (
            <div key={index} className="mb-4">
              <label
                htmlFor={field.name}
                className="block text-gray-700 font-medium mb-2"
              >
                {field.label}
              </label>
              <input
                id={field.name}
                name={field.name}
                type="text"
                onChange={formik.handleChange}
                value={formik.values[field.name]}
                className="border border-gray-400 p-2 rounded-lg w-full"
              />
            </div>
          );
        })}

    ```

I had to add this code我不得不添加这段代码

formik.setFieldValue(`Produkt${fields.length}`, "");
    setFields(fields.filter((_, i) => i !== fields.length - 1));
 useEffect(() => {
    formik.
    formik.setValues({ fields });
  }, [fields]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM