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和onChangeprops,把onEditorStateChange的回调结果传递给onChange,让 Form 自动感知值变化。 - 当表单初始化时,如果没有默认值,用
EditorState.createEmpty()创建空的编辑器状态,避免报错。 - 提交表单时,
values.editor直接就是编辑器的EditorState对象,和你之前手动同步的结果一致,但无需手动调用form.setFieldsValue。
内容的提问来源于stack exchange,提问作者Muhammad Umais Hassan
相关产品推荐
相关产品推荐

