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

Next.js集成react-draft-wysiwyg时无法输入的问题求助

解决react-draft-wysiwyg在Next.js中无法输入的问题

问题背景

在Next.js项目中集成react-draft-wysiwyg富文本编辑器时,尝试用const [editorState, setEditorState] = useState("")接收编辑器输入,但编辑器在本地和Vercel生产环境均无法正常输入,且无任何报错信息,需要通过该状态获取输入内容。

问题原因

react-draft-wysiwyg的editorState属性要求传入的是Draft.js的EditorState对象,而非普通字符串。初始状态设为空字符串会导致编辑器内部状态逻辑异常,无法响应用户输入操作。

解决方案

  1. 初始化正确的EditorState状态
    使用Draft.js提供的EditorState.createEmpty()方法创建空的EditorState对象作为初始值,而非空字符串。

  2. 添加状态更新回调
    给Editor组件绑定onEditorStateChange属性,传入更新状态的回调函数,确保编辑器状态变化时能同步更新本地state。

  3. 转换编辑器内容为字符串(可选)
    如果需要将编辑器内容转为可存储/提交的字符串格式,使用convertToRaw将EditorState转为原始JSON对象,再用JSON.stringify转为字符串。

修改后的完整代码示例

import React, { useCallback, useState } from "react";
import dynamic from "next/dynamic";
import axios from "axios";
import { ContentState, convertToRaw, EditorState } from "draft-js";

const Editor = dynamic(
  () => import("react-draft-wysiwyg").then((mod) => mod.Editor),
  { ssr: false }
);

import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

export default function Home() {
  // 初始化正确的EditorState对象
  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  const handleImageUpload = useCallback(async (file) => {
    try {
      const response = await axios.post(
        // 替换为你的图片上传接口地址
        "/api/upload-image",
        file,
        {
          headers: { "Content-Type": "multipart/form-data" }
        }
      );
      return { data: { link: response.data.url } }; // 根据接口返回结构调整
    } catch (error) {
      console.error("图片上传失败:", error);
      return error;
    }
  }, []);

  // 示例:将编辑器内容转为字符串
  const getEditorContent = () => {
    const contentState = editorState.getCurrentContent();
    const rawContent = convertToRaw(contentState);
    return JSON.stringify(rawContent);
  };

  console.log("当前编辑器状态:", editorState);
  console.log("编辑器内容字符串:", getEditorContent());

  return (
    <div className="container my-5">
      <Editor
        editorState={editorState}
        onEditorStateChange={setEditorState} // 添加状态更新回调
        toolbarClassName="toolbarClassName"
        wrapperClassName="wrapperClassName"
        editorClassName="editorClassName"
        editorStyle={{
          border: "solid 1px lightgray",
          padding: "5px",
        }}
        localization={{ locale: "ja" }}
        toolbar={{
          image: { uploadCallback: handleImageUpload } // 绑定图片上传回调
        }}
      />
    </div>
  );
}

关键修改点说明

  • 初始state从""改为EditorState.createEmpty()
  • 给Editor组件添加onEditorStateChange={setEditorState},确保状态同步
  • 补充了axios的导入和图片上传的基础逻辑(根据实际接口调整)
  • 添加了将EditorState转为字符串的示例方法,方便后续提交或存储

内容的提问来源于stack exchange,提问作者しゅんぺい

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:30:50