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

如何在react-hook-form中使用draft-js-plugins并解决getEditorState报错

问题复现

我正在使用react-hook-form和draft.js作为富文本编辑器,使用draft-js-plugins的代码如下:

import React, {useRef} from "react";
import { Controller } from "./src";
import Editor from "@draft-js-plugins/editor";
import createToolbarPlugin from "@draft-js-plugins/static-toolbar";
import "draft-js/dist/Draft.css";
import "@draft-js-plugins/static-toolbar/lib/plugin.css";

const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];

function RichText({ control }) {
  const editor = useRef(null);
  return (
    <div
      style={{
        border: "1px solid #ccc",
        minHeight: 30,
        padding: 10
      }}
    >
      <Toolbar />
      <Controller
        ref={editor}
        name="DraftJS"
        control={control}
        plugins={plugins}
        render={({ value, onChange }) => {
          return <Editor editorState={value} onChange={onChange} />;
        }}
      />
    </div>
  );
}

export default RichText;

目前代码初始化运行正常,插件可以正常加载显示,但选中文字点击斜体(I)、加粗(B)、下划线(U)等工具栏按钮时,会抛出如下错误:

props.getEditorState is not a function
问题原因

你错误将draft.js需要的plugins参数挂载到了react-hook-form的Controller组件上,Controller仅负责处理表单状态同步,不会处理draft插件相关的属性,也不会注入插件需要的getEditorState方法,插件参数需要直接传递给Editor组件才能生效。

修复方案

将plugins属性从Controller组件移到Editor组件上即可,修改后的完整代码如下:

import React, {useRef} from "react";
import { Controller } from "./src";
import Editor from "@draft-js-plugins/editor";
import createToolbarPlugin from "@draft-js-plugins/static-toolbar";
import "draft-js/dist/Draft.css";
import "@draft-js-plugins/static-toolbar/lib/plugin.css";

const staticToolbarPlugin = createToolbarPlugin();
const { Toolbar } = staticToolbarPlugin;
const plugins = [staticToolbarPlugin];

function RichText({ control }) {
  const editor = useRef(null);
  return (
    <div
      style={{
        border: "1px solid #ccc",
        minHeight: 30,
        padding: 10
      }}
    >
      <Toolbar />
      <Controller
        ref={editor}
        name="DraftJS"
        control={control}
        render={({ value, onChange }) => {
          return <Editor editorState={value} onChange={onChange} plugins={plugins} />;
        }}
      />
    </div>
  );
}

export default RichText;

修改完成后重新运行即可正常使用所有工具栏格式功能,不会再抛出对应错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:39:03