You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React模态框提交表单时同步关闭的实现问题

React表单提交+模态框同步关闭的解决方案

你的问题核心是提交按钮的onClick事件抢在了表单提交逻辑前面执行——直接给提交按钮加props.onClose会让模态框先关掉,表单提交的逻辑还没跑完就被中断了。

直接改两处就行:

  • 删掉提交按钮上的onClick={props.onClose}
  • 在表单提交的处理函数里,等条目添加完成后再调用关闭模态框的方法

修改后的完整代码:

const NewProposal = (props) => {
  const titleRef = useRef("");
  const proposalRef = useRef("");

  function submitHandler(event) {
    event.preventDefault();

    // 这里可以加表单验证逻辑...

    const proposal = {
      title: titleRef.current.value,
      proposal: proposalRef.current.value,
      profilepic: "https://niftyapenation.com/static/media/logo.d41d77f3.png",
      count: 555,
      user: "Ape Nation",
    };

    props.onAddProposal(proposal);
    // 提交完成后再关模态框
    props.onClose();
  }

  return (
    <Modal onClose={props.onClose}>
      <form className={classes.form} onSubmit={submitHandler}>
        <button className={classes.close} onClick={props.onClose}>
          x
        </button>
        <label htmlFor="title">Title</label>
        <input
          type="text"
          className={classes.title_input}
          ref={titleRef}
        ></input>
        <label>Your Proposal</label>
        <textarea
          type="text"
          id="name"
          className={classes.proposal_input}
          ref={proposalRef}
        ></textarea>
        {/* 移除了onClick事件 */}
        <button type="submit" className={classes.post}>Add Proposal</button>
      </form>
    </Modal>
  );
};

export default NewProposal;

这样改完,表单会先把新条目提交成功,然后自动关闭模态框,不用刷新页面就能看到效果。

内容的提问来源于stack exchange,提问作者SL RC CLUB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:18:28