React+Bootstrap联系表单:实现发送按钮禁用及提交后感谢提示
React联系表单提交状态优化方案
解决这个问题的核心是通过React状态控制按钮和提示的显示切换,具体实现步骤如下:
1. 添加状态管理
在你的组件中引入useState钩子,初始化状态变量标记表单是否提交成功:
import { useState } from 'react'; // 组件内部 const [isSubmitted, setIsSubmitted] = useState(false);
2. 修改提交函数sendEmail
更新sendEmail函数,先阻止表单默认刷新行为,邮件发送成功后切换状态,避免重复提交:
const sendEmail = async (e) => { e.preventDefault(); // 阻止页面自动刷新 // 保留你原有的邮件发送逻辑(比如调用API) try { await /* 你的邮件发送异步操作 */; setIsSubmitted(true); // 提交成功后更新状态 } catch (error) { console.error('邮件发送失败:', error); // 可选:失败时可重置状态或提示用户错误 } };
3. 调整表单显示逻辑
根据isSubmitted状态,切换显示“Send”按钮或感谢提示:
<section> <div className="container rounded text-center" style={{ width: '80%', background: "#191919" }}> <h1 style={{ fontFamily: 'Recoleta', color: "#fff" }} id="contact"> Contact Me </h1> <form className="row" style={{ margin: "25px 85px 75px 100px" }} onSubmit={sendEmail}> <label style={{ fontFamily: 'Recoleta', color: "#fff" }}> Name </label> <input type="text" name="name" className="form-control" /> <label style={{ fontFamily: 'Recoleta', color: "#fff" }}> Email </label> <input type="email" name="user_email" className="form-control" /> <label style={{ fontFamily: 'Recoleta', color: "#fff" }}> Message </label> <textarea name="message" rows="4" className="form-control" /> {/* 根据状态切换显示内容 */} {!isSubmitted ? ( <input type='submit' value='Send' className="form-control btn btn-primary" style={{ marginTop: "30px" }} /> ) : ( <div style={{ marginTop: "30px", color: "#fff", fontFamily: 'Recoleta' }}> Thank you for contacting me </div> )} </form> </div> </section>
额外优化(可选)
如果邮件发送需要等待时间,可添加加载状态,避免用户在等待时重复点击:
// 新增加载状态 const [isLoading, setIsLoading] = useState(false); // 更新sendEmail函数 const sendEmail = async (e) => { e.preventDefault(); setIsLoading(true); // 开始加载 try { await /* 邮件发送操作 */; setIsSubmitted(true); } catch (error) { console.error('发送失败:', error); } finally { setIsLoading(false); // 结束加载 } }; // 按钮部分修改 {!isSubmitted ? ( <input type='submit' value={isLoading ? 'Sending...' : 'Send'} className="form-control btn btn-primary" style={{ marginTop: "30px" }} disabled={isLoading} /> ) : ( <div style={{ marginTop: "30px", color: "#fff", fontFamily: 'Recoleta' }}> Thank you for contacting me </div> )}
内容的提问来源于stack exchange,提问作者user20747583
相关产品推荐
相关产品推荐

