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

如何点击Editor组件外的按钮将文本插入react-draft-wysiwyg编辑器光标位置

要实现点击按钮在光标指定位置插入文本,直接使用draft-js 原生的内容操作API即可,不需要来回转换HTML格式,修改后的代码如下:

父组件代码

import EditorWrapper from "./Editor";
import { useState } from "react";

export default function App() {
  const [copy, setCopy] = useState("");
  return (
    <>
      <div className="App">
        <div className="d-flex">
          <button
            onClick={() => setCopy("Welcome")}
            className="btn btn-primary me-2"
          >
            Welcome
          </button>
          <button
            onClick={() => setCopy("Thank you")}
            className="btn btn-primary"
          >
            Thank you
          </button>
        </div>
        {/* 把setCopy也传给子组件,用于插入完成后重置状态 */}
        <EditorWrapper copy={copy} setCopy={setCopy} />
      </div>
    </>
  )
}

Editor组件代码

import "./styles.css";
import React, { useState, useEffect } from "react";
import { Editor } from "react-draft-wysiwyg";
// 新增引入Modifier
import { EditorState, ContentState, convertToRaw, Modifier } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";

export default function EditorWrapper({ copy, setCopy }) {
  const initialState = () => EditorState.createEmpty();
  const [editorState, setEditorState] = useState(initialState);

  // 新增监听copy变化的逻辑,插入文本到光标位置
  useEffect(() => {
    // copy为空时不执行逻辑
    if (!copy) return;
    // 获取当前内容和光标位置
    const currentContent = editorState.getCurrentContent();
    const currentSelection = editorState.getSelection();
    // 在光标位置插入指定文本
    const newContent = Modifier.insertText(currentContent, currentSelection, copy);
    // 生成新的编辑器状态
    const newEditorState = EditorState.push(editorState, newContent, "insert-characters");
    // 插入完成后将光标移动到新插入文本的末尾
    const finalEditorState = EditorState.forceSelection(
      newEditorState,
      newContent.getSelectionAfter()
    );
    // 更新编辑器状态
    setEditorState(finalEditorState);
    // 重置copy状态,避免下次点击相同按钮不触发更新
    setCopy("");
  }, [copy, editorState, setCopy]);

  const onChange = (value) => {
    setEditorState(value);
  };

  return (
    <Editor
      editorState={editorState}
      toolbarClassName="toolbarClassName"
      wrapperClassName="wrapperClassName"
      editorClassName="editorClassName"
      onEditorStateChange={(value) => onChange(value)}
      stripPastedStyles
      ariaLabel="draftEditor"
    />
  );
}

实现说明

  • 核心用了draft-js提供的Modifier.insertTextAPI,该方法会直接在当前选中的光标位置/选区插入指定文本,自动处理内容拼接逻辑
  • 插入完成后调用forceSelection把光标定位到插入文本的末尾,符合普通用户的输入习惯
  • 不需要来回转换HTML格式,既避免了格式丢失的问题,也提升了执行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:36:04