我如何在第一次使用发送按钮后防止再次使用,并在发送按钮后表示感谢?



我在我的网站上有一个联系我的表单,当你按下发送按钮时,它没有给出是否发送的指示,所以我认为人们会垃圾邮件,从而给我几封电子邮件。我该如何停止显示按钮并留下"感谢您与我联系"之类的留言?这是我的表单代码,它是在react和使用bootstrap样式。

<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 style ="/>
<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" /> 
<input type='submit' value='Send' className="form-control btn btn-primary"
style={{marginTop: "30px"}}/>
</form>
</div>

</section>

我已经尝试创建另一个onSubmit,但是它不允许我。

你应该能够在你现有的onSubmit函数中添加一些额外的功能,以使它按照你想要的方式工作。试一下:

const MyForm = () => {
const [hasEmailSent, setHasEmailSent] = useState(false);
const sendEmail = () => {
// keep your current functionality here. Add this line below after the email sends (contain this within an apiCall.status === 200 if statement if the email is being sent with an API)
setHasEmailSent(true);
};
return (
<section>
{hasEmailSent ? (
<div className="container">
<p>Thanks for contacting us!</p>
</div>
) : (
<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 style =" />
<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" />
<input type="submit" value="Send" className="form-control btn btn-primary" style={{ marginTop: '30px' }} />
</form>
</div>
)}
</section>
);
};
export default MyForm;

我添加了一个名为hasEmailSent的布尔值,它只在sendEmail函数结束时被切换为true。在标记中,我添加了一个三元条件,根据hasEmailSent的值显示表单或感谢消息。在这个例子中,感谢信息根本没有样式,所以它很可能需要使用自定义CSS样式,以便看起来更合适。

我建议你研究一下alert()和onclick()函数

你将需要2个状态来保存消息和禁用按钮属性:

const [buttonStatus, setButtonStatus]= useState(false);
const [message, setMessage]= useSate(`send`);

然后使用状态来设置按钮:

<input type='submit' value={message} onClick={() => {setMessage(`sended`); setButtonStatus(true)}} disabled={buttonStatus} className="form-control btn btn-primary" style={{marginTop: "30px"}}/>

最新更新