如何禁用和表单提交按钮后的表单提交在reactJS?



我有一个这样的表单:-

<Form {...layout} form={form} name={formTitle(window.location.pathname)} onFinish={submitForm}>
<Form.Item name="name" label="Name" rules={NAME_VALIDATION}>
<Input value={name} onChange={({ target: { value, } }) => setName(value)}/>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">{formCardTitle(window.location.pathname)}</Button> &nbsp;
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
</Form.Item>
</Form>

我想禁用表单提交的提交按钮。像这样:-

const submitForm = async () => {
.................
.................
// disable submit button
}

我知道如何在表单中禁用按钮,像这样:-

<Button type="primary" htmlType="submit" disabled={!(name)}>
{formCardTitle(window.location.pathname)}
</Button>

但是我想在提交表单后禁用按钮,在submitForm()函数中。我该怎么做呢?

可以使用布尔值

下面是codesandbox 中的实际实现这里有一个例子

import { useState } from "react";
const Form = () => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [btnDisable, setBtnDisable] = useState(false);

const emailHandler = (e) => setEmail(e.target.value);
const nameHandler = (e) => setName(e.target.value);
const submitHandler = (e) => {
e.preventDefault();
if (!name && !email.includes("@")) {
return;
}
const data = { name, email };
// send data to backend;
// after the sent data successfully
setBtnDisable(true);
//clear the input fields
setName("");
setEmail("");
};
return (
<form onSubmit={submitHandler}>
<input type="text" value={name} onChange={nameHandler} />
<input type="email" value={email} onChange={emailHandler} />
<button type="submit" disabled={btnDisable}>
submit
</button>
</form>
);
};
export default Form;

最新更新