WangEditor在React中如何正确获取编辑器内容?

Mc.嘉蕊 阅读 20

我在用WangEditor做富文本编辑功能,但每次调用editor.getHtml()都拿不到最新的内容,是不是哪里初始化错了?

我试过在onChange里存状态,也试过直接调用实例方法,但有时候内容还是旧的,特别在刚输入完就点保存的时候。

const editorRef = useRef(null);
useEffect(() => {
  const editor = new wangEditor(editorRef.current);
  editor.config.onchange = (newHtml) => {
    setContent(newHtml); // 这个setContent是useState的setter
  };
  editor.create();
}, []);
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
UI炳光
UI炳光 Lv1
问题在于useState是异步更新,你刚输入完就点保存,状态还没来得及改。

直接用ref存最新内容,别依赖useState:

const editorRef = useRef(null);
const contentRef = useRef('');

useEffect(() => {
const editor = new wangEditor(editorRef.current);
editor.config.onchange = (newHtml) => {
contentRef.current = newHtml; // 用ref存,不用state
};
editor.create();
return () => editor.destroy();
}, []);

const handleSave = () => {
// 保存时直接从ref拿,或者直接调editor.getHtml()
console.log(contentRef.current);
// 或者 editorRef.current.getHtml()
};


还有个问题,onchange在wangEditor里是配置属性不是事件,可能不生效。改成用编辑器实例的onchange方法:

editor.config.onchange = (newHtml) => {
contentRef.current = newHtml;
};


试试看,基本就是这样。
点赞
2026-03-18 14:19