在React输入元素中按tab键时如何输入空格的制表符大小?

How to input tab size of spaces when press tab key in React input element?

提问人:Salvador Perez 提问时间:11/14/2023 更新时间:11/14/2023 访问量:26

问:

我想在 React 元素中输入空格的选项卡大小。但是当按下 Tab 键时,焦点离开 textarea 或 input,其他 react 元素指向。<textarea><input>

如何捕获此事件并将焦点保持在文本区域或输入上,并将空格的制表符大小添加到当前光标位置?

我试着喜欢这个,但它没有帮助。

const import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [brand, setBrand] = useState("Ford");
  const [description, setDescription] = useState("It's a red color Mustang from 1964");
 
  const setCarBrand = (e) => {
    if(e.keydown == 'tab') setBrand(brand + '     '); 
    else setBrand(e.target.value);
    e.preventDefault();
  }

  const setCarDescription = (e) => {
    if(e.keydown == 'tab') setBrand(brand + '     '); 
    else setDescription(e.target.value);
    e.preventDefault();
  }

  return (
    <>
      <h1>My {brand}</h1>
      <p>
        {description}
      </p>
      <br/>
      <label>{brand}: <label/> <input id="brand" placeholder={brand} value={brand} onChange={setCarBrand} />
      <label>{description} : <label/> <textarea id="description" placeholder={description} value={description} onChange={() => setCarDescription()} />
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
JavaScript ReactJS 选项卡 textarea

评论


答:

1赞 Bob Martin 11/14/2023 #1

您可以在 setCarBrand 和 setCarDescription 函数中添加此代码。

if(e.keyCode === 9) { // tab was pressed
        // get caret position/selection
        var start = this.selectionStart;
        var end = this.selectionEnd;

        var target = e.target;
        var value = target.value;

        // set textarea value to: text before caret + tab + text after caret
        target.value = value.substring(0, start)
                    + "\t"
                    + value.substring(end);

        // put caret at right position again (add one for the tab)
        this.selectionStart = this.selectionEnd = start + 1;

        // prevent the focus lose
        e.preventDefault();
    }