【问题标题】:React antd form disable submit buttonReact antd 表单禁用提交按钮
【发布时间】:2021-03-08 15:30:43
【问题描述】:

如何使用 antd 禁用表单提交按钮

表单验证有效,但是当验证失败时我需要在视觉上禁用表单提交按钮

这是一个 stackblitz 网址 https://stackblitz.com/edit/react-ts-z5d6tr?file=Hello.tsx

【问题讨论】:

标签: reactjs antd


【解决方案1】:

我将在此处粘贴我的解决方案,以防有人发现它有用。 笔记;这个解决方案使用了钩子Form.useForm()和回调onFieldsChange

此摘录中不包含验证。但想法是,当表单更改(任何字段)时,它会将提交按钮(在本例中位于模态框内)设置为禁用/启用。

const LoginForm = () => {
  const [form] = useForm();
  const [disabledSave, setDisabledSave] = useState(true);
  
  const handleFormChange = () => {
    const hasErrors = form.getFieldsError().some(({ errors }) => errors.length);
    setDisabledSave(hasErrors);
  }
  
  return (
    <Modal okButtonProps={{ disabled: disabledSave }} onOk={form.submit}>
      <Form onFieldsChange={handleFormChange} form={form}>
        <Item name="username" label="username">
          <Input />
        </Item>
        <Item name="password" label="password">
          <Input />
        </Item>
      </Form>
    </Modal>
  )
};

【讨论】:

    【解决方案2】:

    我在这里找到了一个不错的解决方案,它不涉及任何额外的状态。如果您像这样将提交按钮包装在Form.Item 中,它应该禁用它,直到完成所有必填字段。表格的其余部分保持不变。

    <Form.Item
     noStyle
     shouldUpdate
    >
      {({ getFieldsValue }) => {
        const { username, password } = getFieldsValue();
        const formIsComplete = !!username && !!password;
        return (
          <Button
             type="primary"
             htmlType="submit"
             disabled={!formIsComplete}
           >
             Log In
           </Button>
        );
      }}
    </Form.Item>
    

    【讨论】:

      【解决方案3】:
      import { UnlockOutlined, UserOutlined } from "@ant-design/icons";
      import { Button, Card, Form, Input, Layout, Space } from "antd";
      import { ValidateErrorEntity } from "rc-field-form/es/interface";
      import React, { useState } from "react";
      import "antd/dist/antd.css";
      
      interface LoginForm {
        username: string;
        password: string;
      }
      
      const Hello = () => {
        // Create State
        const [error, setError] = useState(false);
      
        const onFinish = (values: LoginForm) => {
        };
      
        
      
        const onFinishFailed = (errorInfo: ValidateErrorEntity) => {
          setError(errorInfo); // set the state if error
        };
      
        // When the user starts type set state to false
        const handleChange = e => e.target.value && setError(false);
      
        return (
          <Layout className="login">
            <Card className="card">
              <Form
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                size="large"
                layout="vertical"
              >
                <Space direction="vertical" size="middle">
                  <Form.Item
                    name="username"
                    rules={[
                      { required: true, message: "Please input your username!" }
                    ]}
                  >
                    {/*Listening to change event*/ }
                    <Input onChange={handleChange} prefix={<UserOutlined />} placeholder="Username" />
                  </Form.Item>
      
                  <Form.Item
                    name="password"
                    rules={[
                      { required: true, message: "Please input your password!" }
                    ]}
                  >
                    {/*Listening to change event*/ }
                    <Input.Password
                      onChange={handleChange}
                      prefix={<UnlockOutlined />}
                      placeholder="Password"
                    />
                  </Form.Item>
      
                  <Form.Item className="submit">
                    {/*Disable button only if error is true*/ }
                    <Button disabled={error && true} type="primary" htmlType="submit">
                      Login
                    </Button>
                  </Form.Item>
                </Space>
              </Form>
            </Card>
          </Layout>
        );
      };
      
      export default Hello;
      

      【讨论】:

        【解决方案4】:

        我找到了一些优雅的方法来执行此操作

        <Form.Item shouldUpdate className="submit">
          {() => (
            <Button
              type="primary"
              htmlType="submit"
              disabled={
                !form.isFieldsTouched(true) ||
                form.getFieldsError().filter(({ errors }) => errors.length)
                  .length > 0
              }
            >
              Log in
            </Button>
          )}
        </Form.Item>
        

        【讨论】:

        • 我可以创建一个具有该禁用值的变量吗?我可以在哪里申报,放在哪里?
        • 当前代码不工作,从form.isFieldTouched()删除真值后工作
        【解决方案5】:

        我在这里做了一些修改:https://stackblitz.com/edit/react-ts-spuhdd?file=Hello.tsx

        总结一下我做过的事情:

        1. 我创建了 hooks 用户名、密码和禁用
        2. 每次用户更改用户名和密码时,如果这些字段为空,则将 disabled 设置为 false。
        3. 如果执行了 onFinishFailed,则此 disabled 设置为 true。
        4. 当 disabled 为 true 时,按钮变为禁用状态。如果 disabled 属性变为 false,按钮将再次变为可点击。

        【讨论】:

        • 是的,它可以工作,但是当我们有一些额外的规则时,这会更加复杂,我正在寻找某种react-hook-form 的方法,无论如何谢谢
        猜你喜欢
        • 2016-04-03
        • 2018-06-30
        • 1970-01-01
        • 1970-01-01
        • 2018-10-12
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多