reactjs - 在 React/Bootstrap 4 中,禁用按钮以防止重复表单提交的正确方法是什么?

标签 reactjs button bootstrap-4 form-submit disable

我正在使用 React 16.13 和 Bootstrap 4。我有以下表单容器...

const FormContainer = (props) => {
    ...
  const handleFormSubmit = (e) => {
    e.preventDefault();
    CoopService.save(coop, setErrors, function(data) {
      const result = data;
      history.push({
        pathname: "/" + result.id + "/people",
        state: { coop: result, message: "Success" },
      });
      window.scrollTo(0, 0);
    });
  };

  return (
    <div>
      <form className="container-fluid" onSubmit={handleFormSubmit}>
        <FormGroup controlId="formBasicText">
    ...
          {/* Web site of the cooperative */}
          <Button
            action={handleFormSubmit}
            type={"primary"}
            title={"Submit"}
            style={buttonStyle}
          />{" "}
          {/*Submit */}
        </FormGroup>
      </form>
    </div>
  );

是否有一种标准方法可以禁用提交按钮以防止重复提交表单?问题是,如果从服务器返回的表单中有错误,我希望再次启用该按钮。下面是我上面引用的“CoopService.save”...

...
  save(coop, setErrors, callback) {
    // Make a copy of the object in order to remove unneeded properties
    coop.addresses[0].raw = coop.addresses[0].formatted;
    const NC = JSON.parse(JSON.stringify(coop));
    delete NC.addresses[0].country;
    const body = JSON.stringify(NC);
    const url = coop.id
      ? REACT_APP_PROXY + "/coops/" + coop.id + "/"
      : REACT_APP_PROXY + "/coops/";
    const method = coop.id ? "PUT" : "POST";
    fetch(url, {
      method: method,
      body: body,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          throw response;
        }
      })
      .then((data) => {
        callback(data);
      })
      .catch((err) => {
        console.log("errors ...");
        err.text().then((errorMessage) => {
          console.log(JSON.parse(errorMessage));
          setErrors(JSON.parse(errorMessage));
        });
      });
  }

不确定它是否相关,但这是我的按钮组件。愿意改变它或上面的内容,以帮助实现标准的、开箱即用的方法来解决这个问题。

import React from "react";
  
const Button = (props) => {
  return (
    <button
      style={props.style}
      className={
        props.type === "primary" ? "btn btn-primary" : "btn btn-secondary"
      }
      onClick={props.action}
    >
      {props.title}
    </button>
  );
};

export default Button;

最佳答案

格雷格已经提到过this link向您展示如何使用组件状态来存储按钮是否被禁用。

然而,最新版本的 React 使用带钩子(Hook)的功能组件,而不是 this.statethis.setState(...)。您可以采取以下方法:

import { useState } from 'react';

const FormContainer = (props) => {
  ...
  const [buttonDisabled, setButtonDisabled] = useState(false);
  ...
  const handleFormSubmit = (e) => {
    setButtonDisabled(true); // <-- disable the button here
    e.preventDefault();
    CoopService.save(coop, (errors) => {setButtonDisabled(false); setErrors(errors);}, function(data) {
      const result = data;
      history.push({
        pathname: "/" + result.id + "/people",
        state: { coop: result, message: "Success" },
      });
      window.scrollTo(0, 0);
    });
  };

  return (
    ...
          <Button
            action={handleFormSubmit}
            disabled={buttonDisabled} // <-- pass in the boolean
            type={"primary"}
            title={"Submit"}
            style={buttonStyle}
          />
       ...
  );
const Button = (props) => {
  return (
    <button
      disabled={props.disabled} // <-- make sure to add it to your Button component
      style={props.style}
      className={
        props.type === "primary" ? "btn btn-primary" : "btn btn-secondary"
      }
      onClick={props.action}
    >
      {props.title}
    </button>
  );
};

我编写了一些困惑的内联代码来替换您的 setErrors 函数,但您可能希望将 setButtonDisabled(false); 添加到 setErrors code> 函数,无论您最初定义它的位置,而不是像我一样从匿名函数调用它;所以请记住这一点。

有关 useState Hook 的更多信息可以找到 here 。如果这能回答您的问题,请告诉我。

关于reactjs - 在 React/Bootstrap 4 中,禁用按钮以防止重复表单提交的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63414348/

相关文章:

ReactJS:根据点击事件更改路线

javascript - 如何在功能组件 [React] 中设置 displayName

ruby-on-rails - 在 Rails 中使用 Bootstrap gem

python - 使用 "show more "来抓取数据

excel - 如何在 VBA 中以编程方式在某些工作表单元格数据旁边添加按钮?

CSS: div 搜索元素右对齐 (Bootstrap)

javascript - Bootstrap 4.1.1 页脚与右边框居中对齐

node.js - 如何正确在线上传本地主机网站?

javascript - 在 github、youtube 上显示每条路线更改的进度

android - 如何将 Material 按钮与其他 UI 元素对齐