防止 React 捕获制表符 [英] Prevent React from capturing tab character

查看:47
本文介绍了防止 React 捕获制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段.我想让 React 检查是否在此字段中按下了选项卡.如果是,则处理该字段的内容(例如 ajax 调用).

I have an input field. I want React to check if a tab has been pressed in this field. If so, then process the contents of that field (e.g. ajax call).

getInitialState: function() {
  return { name: "" }; 
},

handleChangeName: function(e) {
  this.setState({name: e.target.value});
},

handleKeyUp: function(e) {
  if (e.keyCode == 9) {
    e.preventDefault();
    alert("Execute ajax call after tab pressed");
  }
},

<input type="text" value={this.state.name} onChange={this.handleChangeName}
   onKeyDown={this.handleKeyUp} />

问题:

Tab 按键被拦截并执行后续代码,但将制表符插入到输入文本字段中.我如何防止这种情况发生?

Tab keypress is intercepted and subsequent code executed but the tab character is inserted into the input text field. How do I prevent this from happening?

我尝试了 preventDefaultstopPropagationstopImmediatePropagation 的各种组合.我可以得到没有在输入文本字段中插入更多字符的结果,但随后没有执行任何代码.

I have tried various combinations of preventDefault, stopPropagation, stopImmediatePropagation. I can get a result of no further chars being inserted into the input text field, but then no subsequent code is executed.

我错过了什么?

推荐答案

onKeyUponKeyPress 事件在 'Tab 时不会被调用>' 被按下是因为它之前触发了 onBlur,你需要用 onKeyDown 来捕捉它.您可以尝试使用事件 key 而不是 keyCode,如上例所示.

The events onKeyUp or onKeyPress won't be called when 'Tab' is pressed because it triggers a onBlur before, you need to catch it with onKeyDown. You can try to use the event key instead of keyCode, as the example above.

功能:

 handleKeyDown: function(e) {
    if (e.key === "Tab") {
      e.preventDefault();
      alert("Execute ajax call after tab pressed");
    }
  }

输入:

<input type="text" onKeyDown={this.handleKeyDown} />

希望对您有所帮助;)

这篇关于防止 React 捕获制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆