【发布时间】:2025-11-30 14:30:02
【问题描述】:
我正在使用 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));
});
});
}
不确定它是否相关,但这是我的 Button 组件。愿意更改它或上述内容以帮助实施一种标准的、开箱即用的方法来解决这个问题。
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;
【问题讨论】:
-
另一种解决方案可能是使用模式,因为您一次只能打开一个。我经常使用这种方法来保存表单。
-
谢谢@GregH。你的建议似乎是我喜欢的自定义解决方案,但我觉得我不是第一个想要这样的人 - 你认为有什么开箱即用的解决方案或方法吗?可以构建事物以最小化我必须编写的自定义代码的数量来适应这样的事情吗?
-
见*.com/questions/55579068/… 避免多次点击按钮反应的方法是使用带状态的禁用道具。将您的 save() 函数更改为异步。在 save() 的顶部,将保存状态设置为 true(按钮将被禁用),一旦完成保存,将状态设置为 false(启用按钮)。
-
谢谢,但您链接到的答案似乎是使用“this.setState”范式,而我使用的是较新的“const [myItem setMyItem] = useState(...)”范式(不是确定将这两件事称为的正确方法)。
-
回复:
const [myItem setMyItem] = useState(...)。它非常相似。而不是this.setState({state: newState})只是做setMyItem(newState)
标签: reactjs button bootstrap-4 form-submit disable