[英]Textfield is not allowing me to enter characters on keypress in Firefox
[英]Ability to enter tab characters in a TextField?
我有一个定义为多行的 MUI TextField
。 我的目标是输入 JSON 文本。 我发现当我按下 Tab 键时,我的组件失去了焦点,焦点被转移到了屏幕上的下一个组件。 我想要的是将制表符值 (\\t) 输入到字符串文本中。 是否有禁用 Tab 键作为导航工具的方法?
默认情况下,如果您在input
字段中按Tab ,浏览器会将焦点切换到下一个元素。 要覆盖该行为,您可以监听keydown
事件并调用e.preventDefault()
,然后添加一些代码以在光标位置插入制表符。 下面是实现。 请注意,由于您正在篡改输入value
,因此撤消功能不再起作用:
<TextField
multiline
onKeyDown={(e) => {
const { value } = e.target;
if (e.key === 'Tab') {
e.preventDefault();
const cursorPosition = e.target.selectionStart;
const cursorEndPosition = e.target.selectionEnd;
const tab = '\t';
e.target.value =
value.substring(0, cursorPosition) +
tab +
value.substring(cursorEndPosition);
// if you modify the value programmatically, the cursor is moved
// to the end of the value, we need to reset it to the correct
// position again
e.target.selectionStart = cursorPosition + 1;
e.target.selectionEnd = cursorPosition + 1;
}
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.