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

6l7fqoea  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(144)

我想在React元素的<textarea><input>中输入空格的制表符大小。但是当按Tab键时,焦点离开了文本区域或输入,其他react元素被指向。
我如何捕捉这个事件,并保持焦点到文本区域或输入,并添加一个空格的制表符大小到当前光标位置?
我试着喜欢它,但它没有帮助。

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 />);

字符串

2ic8powd

2ic8powd1#

您可以将此代码添加到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();
    }

字符串

相关问题