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

点击React按钮弹出“离开此网站?”提示框的问题排查

问题原因

你的按钮是type="submit"且嵌套在<form>标签内,点击时会触发表单默认提交行为——浏览器会尝试刷新页面提交表单,因此弹出“Leave site?”的提示,此时你的signIn函数虽会执行,但页面即将刷新,可能导致你看不到控制台日志,同时触发浏览器的离开确认提示。

解决方案

可以通过以下几种方式解决:

方法1:阻止表单默认提交行为

修改signIn函数,添加event.preventDefault()来阻断表单的默认提交逻辑:

const signIn = (e) => {
  e.preventDefault(); // 阻止表单默认提交行为
  console.log("InfoLgnTest singin clicked");
}

同时确保按钮的onClick传递事件参数:

<input type="submit" onClick={signIn}/>

更规范的写法是直接给<form>绑定onSubmit事件,而非给按钮绑定onClick:

<form onSubmit={signIn}>
  {/* 输入框内容 */}
  <div className="button-container">
    <input type="submit" />
  </div>
</form>

对应函数:

const signIn = (e) => {
  e.preventDefault();
  console.log("InfoLgnTest singin clicked");
}

方法2:修改按钮类型为button

把提交按钮的type从submit改为button,这样不会触发表单的默认提交行为:

<div className="button-container">
  <input type="button" onClick={signIn} value="提交"/>
</div>

方法3:移除<form>标签

如果你的组件不需要原生表单的默认功能(比如原生校验、提交等),可以直接去掉<form>标签,用普通<div>包裹输入框和按钮:

return (
  <>
    <div className="form">
      <div className="input-container">
        <label>Username </label>
        <input 
          name="email"
          type="text" 
          ref={emailRef}
          required 
          placeholder ="something@gmail.com"
        />
      </div>
      <div className="input-container">
        <label>Password </label>
        <input 
          type="text" 
          name="pass" 
          ref={passwordRef}
          required 
          placeholder ="..."
        />
      </div>
      <div className="button-container">
        <input type="button" onClick={signIn}/>
      </div>
    </div>
  </>
)

额外提醒

你的InfoLgnTest类组件存在一个小问题:this.state不能定义在render方法内,应该放在构造函数中或使用类属性语法:

// 构造函数方式
class InfoLgnTest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: null
    };
  }

  render() {
    return (
      <div>
        <div className="App">
          <SignInWithEmailPassword />
        </div>
      </div>
    );
  }
}

// 类属性语法
class InfoLgnTest extends Component {
  state = {
    user: null
  };

  render() {
    return (
      <div>
        <div className="App">
          <SignInWithEmailPassword />
        </div>
      </div>
    );
  }
}

内容的提问来源于stack exchange,提问作者BRDroid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:16:20