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

React表单输入框按下回车时禁止页面回退的实现方案

React表单输入框回车阻止页面回退/实现跳转下一个输入框

方案一:阻止回车默认行为(按下回车无响应)

直接在表单元素上添加onKeyDown事件,捕获输入框的回车操作并阻止默认行为,避免触发表单提交或页面回退:

<form 
  id='createForm' 
  className="row mt-4" 
  onSubmit={handleSubmit}
  onKeyDown={(e) => {
    if (e.key === 'Enter' && e.target.tagName === 'INPUT') {
      e.preventDefault();
    }
  }}
>
  {/* 原有表单内容 */}
</form>

如果只想针对单个输入框生效,也可以给对应的Field组件单独绑定事件:

<Field
  className="form-control"
  type="text"
  name='title'
  component="input"
  onKeyDown={(e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
    }
  }}
/>

方案二:按下回车自动跳转到下一个输入框

通过给输入框设置连续的tabIndex和全局回车事件,实现按回车切换到下一个输入框的效果:

  1. 给每个Field组件设置连续的tabIndex值:
<Field
  className="form-control"
  type="text"
  name='title'
  component="input"
  tabIndex={1}
/>
<Field
  className="form-control"
  type="textarea"
  name='text'
  component="input"
  tabIndex={2}
/>
<Field
  className="form-control"
  type="link"
  name="link"
  component="input"
  tabIndex={3}
/>
<Field
  className="form-control"
  type="text"
  name='link_title'
  component="input"
  tabIndex={4}
/>
  1. 在表单上添加onKeyDown事件,实现跳转逻辑:
<form 
  id='createForm' 
  className="row mt-4" 
  onSubmit={handleSubmit}
  onKeyDown={(e) => {
    if (e.key === 'Enter' && e.target.tagName === 'INPUT') {
      e.preventDefault();
      const currentTabIndex = parseInt(e.target.tabIndex);
      const nextInput = document.querySelector(`[tabindex="${currentTabIndex + 1}"]`);
      if (nextInput) nextInput.focus();
    }
  }}
>
  {/* 输入框内容 */}
</form>

补充说明

页面回退通常是因为回车触发了表单的默认提交行为,进而间接引发页面跳转。通过上述方案阻止回车的默认行为,即可避免该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:55:16