Kol*_*ban 3 javascript reactjs material-ui
我有一个TextField被定义为多行的 MUI。我的目标是输入 JSON 文本。我发现当我按下 Tab 键时,我的组件失去焦点,焦点转移到屏幕上的下一个组件。我想要的是将制表符值 (\t) 输入到字符串文本中。有没有办法禁用 Tab 键作为导航工具?
默认情况下,如果您按下Tab该input字段,浏览器会将焦点切换到下一个元素。要覆盖该行为,您可以侦听该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;
}
}}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |