reactjs 最终表单- useField钩子验证器

qpgpyjmq  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(140)

我正在尝试添加一个使用useField构建的表单字段。我还希望根据字段是否被禁用来动态关闭所需的验证。即使组件正在重新呈现,验证也不会被删除。
下面是https://codesandbox.io/s/zen-zhukovsky-woicvh?file=/index.js的示例

    • 索引. js**
import React, { useState } from "react";
import { render } from "react-dom";
import { Form } from "react-final-form";
import TextField from "./TextField";

const App = () => {
  const [isDisabled, setIsDisabled] = useState(false);
  const onSubmit = async (values) => {
    alert("Submit Successful");
  };

  return (
    <>
      <div>{isDisabled ? "is" : "is not"} disabled</div>
      <input
        type="checkbox"
        onChange={(value) => setIsDisabled(value.target.checked)}
      />
      <Form
        onSubmit={onSubmit}
        render={({ handleSubmit }) => (
          <form onSubmit={handleSubmit}>
            <div>
              <TextField
                name="firstName"
                type="text"
                placeholder="First Name"
                disabled={isDisabled}
                required={!isDisabled}
              />
            </div>
            <div>
              <button type="submit">Submit</button>
            </div>
          </form>
        )}
      />
    </>
  );
};

render(<App />, document.getElementById("root"));
    • 文本字段. js**
import React from "react";
import { useField } from "react-final-form";

const requiredValidator = (value) =>
  !value || !value.length ? "required" : false;

const TextField = ({ label, ...props }) => {
  const { required, ...rest } = props;

  const { input, meta } = useField(props.name, {
    validate: required ? requiredValidator : null
  });

  return (
    <>
      <label>
        {label}
        <input {...input} {...rest} />
      </label>
      {meta.error && meta.touched && <span>{meta.error}</span>}
    </>
  );
};
export default TextField;

通过勾选该框,它将禁用/启用文本框,这将依次删除验证。即禁用框=不需要
但它总是被要求的,我不明白为什么。

von4xj4u

von4xj4u1#

同样的问题。Required为false,但validate不更新

相关问题