简体   繁体   English

能否在 TextField 中输入制表符?

[英]Ability to enter tab characters in a TextField?

I have a MUI TextField that is defined as multi-line.我有一个定义为多行的 MUI TextField My goal is to enter JSON text.我的目标是输入 JSON 文本。 I found that when I pressed the tab key, my component lost focus and focus was given to the next component on screen.我发现当我按下 Tab 键时,我的组件失去了焦点,焦点被转移到了屏幕上的下一个组件。 What I desire is to have the tab value (\\t) entered into the string text.我想要的是将制表符值 (\\t) 输入到字符串文本中。 Is there a recipe to disable the tab key as a navigation tool?是否有禁用 Tab 键作为导航工具的方法?

By default, if you press Tab in the input field, the browser will switch focus to the next element.默认情况下,如果您在input字段中按Tab ,浏览器会将焦点切换到下一个元素。 To override that behavior, you can listen to the keydown event and call e.preventDefault() , then add some code to insert the tab character at the cursor position.要覆盖该行为,您可以监听keydown事件并调用e.preventDefault() ,然后添加一些代码以在光标位置插入制表符。 Below is the implementation.下面是实现。 Note that because you are tampering with the input value , the undo feature doesn't work anymore:请注意,由于您正在篡改输入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;
    }
  }}
/>

Live Demo现场演示

代码沙盒演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM