在 React 中,Input 失去焦点时获取失去焦点的位置并插入值

实现思路:

  1. 监听 Input 失去焦点 (onBlur) 事件 :在 onBlur 事件中,我们可以获取光标的当前位置以及 Input 中的值。
  2. 使用 onClick 或 onMouseDown 事件来获取点击的其他位置:通过全局点击监听,获取点击的目标元素。
  3. 插入值到光标位置 :通过 DOM 的 selectionStart 和 selectionEnd 来确定光标位置,进而插入新的值。

示例代码:

javascript 复制代码
import React, { useState, useRef } from 'react';

const InputWithInsert = () => {
  const [inputValue, setInputValue] = useState('');  // Input的值
  const inputRef = useRef(null);  // 引用 Input 组件
  const [focusPosition, setFocusPosition] = useState(null); // 光标位置

  // 监听 Input 的变化
  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  // 监听 Input 失去焦点时,记录光标位置
  const handleBlur = (e) => {
    const input = inputRef.current;
    if (input) {
      const cursorPosition = input.selectionStart;  // 获取失去焦点时的光标位置
      setFocusPosition(cursorPosition);
    }
  };

  // 插入值到光标位置
  const insertValueAtCursor = (value) => {
    const input = inputRef.current;
    if (input && focusPosition !== null) {
      const beforeCursor = inputValue.substring(0, focusPosition);
      const afterCursor = inputValue.substring(focusPosition);
      const newValue = beforeCursor + value + afterCursor;
      setInputValue(newValue);
    }
  };

  // 模拟点击插入值
  const handleClickInsert = () => {
    insertValueAtCursor('[插入内容]');  // 模拟插入内容
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        onBlur={handleBlur}  // 监听失去焦点事件
        ref={inputRef}       // 引用 Input 组件
      />
      <button onClick={handleClickInsert}>插入值</button>
    </div>
  );
};

export default InputWithInsert;
  • inputRef :用来引用 <input> 元素,以便在失去焦点时获取光标位置。
  • handleBlur :在 Input 失去焦点时记录光标位置(使用 selectionStart 获取光标的位置)。
  • insertValueAtCursor:根据失去焦点时保存的光标位置,将指定的内容插入到该位置。
相关推荐
JavaGuide9 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02179 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013849 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk816310 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen10 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus10 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing10 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真11 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup11 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法11 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端