React Modal内表单提交失效:无事件触发问题排查
问题原因与修复方案
核心问题是:提交按钮(Senden)不在<form>标签内部,导致点击按钮时无法触发表单的onSubmit事件,handleSubmit函数自然不会执行。
修复步骤
- 将包含两个按钮的
<div>容器移动到<form>标签内部,让type="submit"的按钮与表单建立关联。 - 移除表单的
action="Post"属性,因为你已经通过onSubmit自定义了提交逻辑,避免默认行为冲突。 - 给“Abbrechen”按钮添加
type="button"属性,防止它默认触发表单提交(HTML中button默认type为submit)。
修改后的关键代码片段
<form onSubmit={handleSubmit} className="mt-5 flex flex-col justify-between"> {/* 原有输入项(姓名、邮箱、消息)保持不变 */} {/* 按钮容器移到form内部 */} <div className="mt-5 flex gap-x-4 justify-center items-center"> <button type="submit" className="w-full text-white rounded-md py-4 hover:bg-secondary-green-300 bg-secondary-green-400" > Senden </button> <button type="button" className="w-full text-white rounded-md py-4 hover:bg-secondary-red-100 bg-secondary-red-300" onClick={closeModal} > Abbrechen </button> </div> </form>
额外优化建议
successfulSubmission初始值设为null或false,避免后续赋值布尔值时出现类型不一致的问题。
内容的提问来源于stack exchange,提问作者WorkoutBuddy
相关产品推荐
相关产品推荐

