【问题标题】:React: Insert value at cursor反应:在光标处插入值
【发布时间】:2021-03-23 21:31:49
【问题描述】:

我需要添加一个值(从下拉列表中),这将添加到输入字段中的“光标位置”:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [cur, setCur] = useState("");
  const [state, setState] = useState("");
  const [dropVal, setDropVal] = useState("");

  const handleChange = (e) => {
    setState(e.target.value);
    // gives cursor index 
    // this only shows cursor position if user types 
    // I need to track the position of the cursor and add dropVal there
    setCur(e.target.selectionStart); 
  };
  
  return (
    <div className="App">
      <input onChange={(e) => handleChange(e)} value={state} />
      <select onChange={(e) => setDropVal(e.target.value)} >
        <option>ONE</option>
        <option>TWO</option>
      </select>  
    </div>
  );
}

我试过这个,这是不完整的,找不到在任何地方实现它的方法。 感谢您的帮助,在此先感谢!

【问题讨论】:

    标签: javascript reactjs react-native react-redux


    【解决方案1】:

    您要查找的是输入字段上的 selectionStartselectionEnd 属性。

    基本上,您可以在输入字段上附加一个onBlur 侦听器,在其中您可以访问selectionStart 属性并将其保存在状态中。

    模糊意味着输入字段失去了焦点(意味着您点击了外部的某个地方 - 就像我们的例子中的下拉菜单一样)。所以一旦触发了 onBlur,selectionStart 指的是你的光标所在的位置,而输入仍然是焦点。

    稍后您可以使用此值来断开字符串并在光标位置添加您想要的任何内容(在本例中为选项值)。

    const onBlur = (e) => {
        setCur(e.target.selectionStart);
    };
    

    Have a look at this code sandbox

    【讨论】:

    • 嘿卡兰。你能检查一下这是否有效吗?
    猜你喜欢
    • 2014-04-20
    • 2015-10-18
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多