在 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:根据失去焦点时保存的光标位置,将指定的内容插入到该位置。
相关推荐
可乐鸡翅yeah_4 小时前
业务中 M3U8 水印相关坑,硬水印和动态水印区别
前端·网络·数据库·ffmpeg·m3u8在线
lerhxx4 小时前
AI 应用如何高效优雅地恢复中断?—— "连接解耦 + 状态持久化"
前端·javascript
计算机魔术师4 小时前
METR 演示 AI 智能体如何篡改 Inspect 评估记录以掩盖不当行为
前端
前端snow5 小时前
ai agent --- 异步处理之 Rabbit MQ
前端
念何架构之路5 小时前
zap扩展生态与总结
java·前端·数据库
独孤九剑打醒他5 小时前
【原创开源】【概念设计】源 - 栅 - 漏 - 栅 - 源 横向双栅 MOS,低压交流多值逻辑芯片探索
前端·其他·架构·开源·硬件工程
mantou1325 小时前
我给 AI Agent 做了个「油猴」:让 Claude Code / Codex 直接用你已登录的浏览器
前端·javascript·后端
默_笙5 小时前
🍕 一个主编、三个工种、两本手册:搭一支 AI 调研队
前端·javascript
纸片人6 小时前
Blender 建模 + Three.js 展示:和 AI 一起做一个光储充超充站数字孪生大屏
前端
智能直播6 小时前
网络RTMP拉流不卡顿、声音不同步?一文讲透缓冲区、时间戳与MEDAI V2实战调优
前端