【问题标题】:input cursor is not staying where it is placed it is going again at the last of input text输入光标没有停留在它所在的位置,它会在输入文本的最后一个位置再次移动
【发布时间】:2022-01-09 07:50:27
【问题描述】:

代码如下:

 const [expression, setExpression] = useState("");

 const Remove = () => {        
    const input = document.getElementById("input");
    if (expression.length > 0) {
        const pos = input.selectionStart;
        if (pos > 0) {
     setExpression(expression.substring(0, pos - 1) + expression.substring(pos));
          input.focus();
          input.selectionStart = pos - 1;
          input.selectionEnd = pos - 1;
        }
      }
}

return (
<>
<input id="input" value={expression} />
<button onClick={Remove}>remove</button>
</>
)

我想在单击按钮时删除光标位于输入框中的文本,但在删除数字后光标在输入文本的末尾一次又一次地移动。我希望它保持在输入字段中的位置,而不是放在输入框文本的末尾。

【问题讨论】:

    标签: html reactjs


    【解决方案1】:

    您可以通过 有状态无状态 的方式进行操作。

    有状态

      const [expression, setExpression] = useState("");
      const [cursorPos, setCursorPos] = useState(0);
    
      useEffect(() => {
        const input = document.getElementById("input");
        input.focus();
        input.setSelectionRange(cursorPos, cursorPos);
      }, [cursorPos, expression]);
    
      const handleInput = (e) => {
        setExpression(e.target.value);
        const input = document.getElementById("input");
        setCursorPos(input.selectionStart);
      }
    
      const Remove = () => {
        const input = document.getElementById("input");
        if (expression.length > 0) {
          const pos = input.selectionStart;
          if (pos > 0) {
            setExpression(
              expression.substring(0, pos - 1) + expression.substring(pos)
            );
            setCursorPos(pos - 1);
          }
        }
      };
    
      return (
        <>
          <input id="input" value={expression} onInput={handleInput} />
          <button onClick={Remove}>remove</button>
        </>
      );
    

    无状态,使用 ref

      const inputRef = useRef();
    
      const Remove = () => {
        const input = inputRef.current;
        const value = input.value;
        if (value.length > 0) {
          const pos = input.selectionStart;
          if (pos > 0) {
            input.value = value.substring(0, pos - 1) + value.substring(pos);
            input.focus();
            input.selectionStart = pos - 1;
            input.selectionEnd = pos - 1;
          }
        }
      };
    
      return (
        <>
          <input id="input" ref={inputRef} />
          <button onClick={Remove}>remove</button>
        </>
      );
    

    【讨论】:

    • @DhruvDhing 欢迎您!通常提问者将有用的答案标记为accepted,这会增加回答者和他自己的声誉。它还有助于其他人了解问题已得到解答并轻松找到答案。但这不是强制性的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多