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

react-draft-wysiwyg能否与Antd Form配合?为何无法自动捕获值?

问题解答

你的猜想完全正确:Antd Form 默认会监听表单组件的 onChange 事件来自动收集字段值,但 react-draft-wysiwyg 的编辑器组件暴露的是 onEditorStateChange 回调,而非标准的 onChange,这就是无法自动捕获值的核心原因。

你可以通过封装一个适配层组件,将 onEditorStateChange 映射为 Antd Form 期望的 onChange,实现自动值捕获,无需手动调用 form.setFieldsValue。

实现代码

import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { Form, Button } from "antd";
import { EditorState } from "draft-js";

// 封装适配Antd Form的编辑器组件
const DraftEditor = ({ value, onChange, ...restProps }) => {
  return (
    <Editor
      editorState={value ?? EditorState.createEmpty()}
      onEditorStateChange={(editorState) => onChange(editorState)}
      {...restProps}
      style={{ border: "1px solid black" }}
    />
  );
};

export default function App() {
  const [form] = Form.useForm();

  const handleFinish = (values) => {
    console.log("表单提交值:", values);
    // 这里可以直接拿到editor字段对应的EditorState
  };

  return (
    <Form form={form} onFinish={handleFinish}>
      <Form.Item name="editor">
        <DraftEditor
          toolbarClassName="toolbarClassName"
          wrapperClassName="wrapperClassName"
          editorClassName="editorClassName"
        />
      </Form.Item>
      <Button htmlType="submit">提交</Button>
    </Form>
  );
}

关键说明

  • 封装的 DraftEditor 组件接收 Antd Form 传入的 value 和 onChange props,把 onEditorStateChange 的回调结果传递给 onChange,让 Form 自动感知值变化。
  • 当表单初始化时,如果没有默认值,用 EditorState.createEmpty() 创建空的编辑器状态,避免报错。
  • 提交表单时,values.editor 直接就是编辑器的 EditorState 对象,和你之前手动同步的结果一致,但无需手动调用 form.setFieldsValue。

内容的提问来源于stack exchange,提问作者Muhammad Umais Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:57:13