You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在textarea光标位置插入来自选择器的姓名标签

React 实现textarea光标处插入指定文本方案

核心逻辑是通过textarea DOM的原生属性获取光标位置,拼接内容后重置光标位置即可完成需求,具体实现如下:

实现步骤

  • 用useRef绑定textarea元素,获取原生DOM操作权限
  • 点击变量按钮时,读取textarea的selectionStart(光标起始位置)、selectionEnd(光标结束位置)属性
  • 将原有内容按光标位置拆分,拼接插入的变量内容后更新textarea绑定的状态
  • 内容更新后将光标重置到插入变量的末尾位置,保证后续输入体验

完整代码示例

import { useState, useRef, useEffect } from 'react';

function TemplateEditor() {
  // 绑定textarea的内容状态
  const [content, setContent] = useState('尊敬的Mr:您好');
  // 绑定textarea的ref
  const textareaRef = useRef(null);
  // 存储插入变量后光标需要移动到的位置
  const [targetCursorPos, setTargetCursorPos] = useState(null);

  // 内容更新后,调整光标位置
  useEffect(() => {
    if (targetCursorPos !== null && textareaRef.current) {
      textareaRef.current.focus();
      textareaRef.current.selectionStart = targetCursorPos;
      textareaRef.current.selectionEnd = targetCursorPos;
      // 重置标记位
      setTargetCursorPos(null);
    }
  }, [content, targetCursorPos]);

  // 插入变量的公共方法
  const handleInsertVariable = (variableStr) => {
    const textareaDom = textareaRef.current;
    if (!textareaDom) return;

    // 获取当前选中/光标位置
    const startPos = textareaDom.selectionStart;
    const endPos = textareaDom.selectionEnd;

    // 拼接新内容
    const newContent = content.slice(0, startPos) + variableStr + content.slice(endPos);
    setContent(newContent);
    // 计算插入后光标位置:原光标起始位置 + 插入的变量长度
    setTargetCursorPos(startPos + variableStr.length);
  };

  return (
    <div style={{ padding: '20px' }}>
      {/* 变量按钮组 */}
      <div style={{ marginBottom: '10px' }}>
        <button onClick={() => handleInsertVariable('$name')}>$name</button>
        {/* 可扩展其他变量按钮 */}
        {/* <button onClick={() => handleInsertVariable('$date')}>$date</button> */}
      </div>
      <textarea
        ref={textareaRef}
        value={content}
        onChange={(e) => setContent(e.target.value)}
        rows={6}
        cols={60}
        placeholder="请输入内容..."
      />
    </div>
  );
}

export default TemplateEditor;

补充说明

  • 上述代码默认支持选中文本后点击变量直接替换选中内容的效果
  • 如果需要插入的变量是带特殊格式的富文本内容,需要换用contenteditable属性的div实现,textarea不支持富文本内容

内容的提问来源于stack exchange,提问作者Minh Huy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:57:03