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

React-draft-wysiwyg编辑器回显后端数据后无法编辑求助

React-draft-wysiwyg回显后无法编辑&状态绑定异常问题解决

问题分析

你当前的代码存在两个核心问题:

  1. 直接在组件顶层同步创建editorState并作为useState初始值,若sendDescription是异步获取的(比如从后端API请求),初始渲染时sendDescription可能还未返回,导致初始状态异常;同时每次组件渲染都会重复创建EditorState实例,干扰编辑器的状态更新逻辑,引发无法编辑的问题。
  2. 尝试绑定description时编辑器为空,是因为初始useState的赋值逻辑没有在异步数据返回后更新状态。

修正后的代码示例

1. 状态初始化与异步数据处理

import { useState, useEffect } from 'react';
import { EditorState, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'; // 别忘了引入编辑器样式

const YourEditorComponent = ({ sendDescription }) => {
  // 初始化为空编辑器状态
  const [description, setDescription] = useState(EditorState.createEmpty());

  const onEditorStateChange = (newEditorState) => {
    setDescription(newEditorState);
  };

  // 当后端返回的sendDescription变化时,转换HTML为EditorState并更新状态
  useEffect(() => {
    if (sendDescription) {
      const html = sendDescription.toString();
      const contentBlock = htmlToDraft(html);
      if (contentBlock) { // 确保HTML转换成功
        const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
        const editorState = EditorState.createWithContent(contentState);
        // 将光标移到内容末尾,确保编辑器进入可编辑状态
        const focusedEditorState = EditorState.moveFocusToEnd(editorState);
        setDescription(focusedEditorState);
      }
    }
  }, [sendDescription]); // 依赖sendDescription,数据更新时自动触发转换

  // 你的内容状态处理函数
  const onContentStateChangeJSon = (contentState) => {
    // 这里编写你的内容状态变化逻辑
  };

  return (
    <Editor
      editorState={description}
      onEditorStateChange={onEditorStateChange}
      toolbarClassName="toolbarClassName"
      wrapperClassName="wrapperClassName"
      editorClassName="editorClassName"
      onContentStateChange={onContentStateChangeJSon}
    />
  );
};

export default YourEditorComponent;

关键修正点

  • 异步数据处理:用useEffect监听sendDescription的变化,只有当数据存在时才进行HTML到EditorState的转换,避免初始渲染时的空值问题。
  • 状态唯一来源:编辑器始终绑定description状态,确保所有状态更新都通过setDescription完成,避免临时变量干扰。
  • 转换结果校验:增加contentBlock的存在性判断,避免转换失败时引发错误。
  • 光标聚焦处理:转换后调用EditorState.moveFocusToEnd,确保编辑器进入可编辑状态。

关于你尝试的两种写法

  • 方法1能显示内容但无法编辑:因为你直接使用了组件顶层创建的editorState临时变量,这个变量在每次渲染都会重新创建,编辑器无法追踪状态变化,导致无法触发编辑更新。
  • 方法2编辑器为空:因为初始useState赋值时sendDescription可能还未返回,editorState是基于空值生成的,且没有后续的状态更新逻辑,所以显示为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:45:32