简体   繁体   中英

Ability to enter tab characters in a TextField?

I have a MUI TextField that is defined as multi-line. My goal is to enter JSON text. I found that when I pressed the tab key, my component lost focus and focus was given to the next component on screen. What I desire is to have the tab value (\\t) entered into the string text. Is there a recipe to disable the tab key as a navigation tool?

By default, if you press Tab in the input field, the browser will switch focus to the next element. 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. Below is the implementation. Note that because you are tampering with the input value , the undo feature doesn't work anymore:

<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

代码沙盒演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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