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

React中Sun Editor默认值设置问题:从数据库取值无效

React中Sun Editor数据库默认值设置问题

问题场景

尝试为React的Sun Editor设置来自数据库的默认值,使用defaultValue={guide.description}无效,但直接传入HTML字符串形式的默认值(如defaultValue={"<p>The editor's default value</p>"})即可正常生效。

解决方案

1. 检查数据的类型与格式

首先确认guide.description的实际内容:

  • 用console.log(typeof guide.description, guide.description)打印,确保它是字符串类型,且内容是未被转义的原始HTML(比如直接是<p>xxx</p>,而非&lt;p&gt;xxx&lt;/p&gt;)。
  • 如果数据被转义(出现&lt;、&gt;等实体字符),需要解码为原始HTML:
    // 用DOMParser解码
    const decodeHtml = (html) => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      return doc.documentElement.textContent;
    };
    
    // 使用时
    defaultValue={decodeHtml(guide.description)}
    
    或者使用第三方库(如he)进行解码:
    npm install he
    
    import he from 'he';
    defaultValue={he.decode(guide.description)}
    

2. 确保数据已加载完成

如果是异步从数据库获取数据,初始渲染时guide.description可能为undefined或空值,导致编辑器无法读取默认值。需添加条件渲染:

{guide?.description && (
  <SunEditor
    autoFocus={true}
    onChange={handleEditorChange}
    setOptions={toolbarOptions}
    defaultValue={guide.description}
  />
)}

3. 手动调用API设置内容

如果defaultValue仍不生效,可通过编辑器的setContents方法手动设置:

import { useRef, useEffect } from 'react';

const YourComponent = () => {
  const editorRef = useRef(null);

  useEffect(() => {
    if (guide.description && editorRef.current) {
      editorRef.current.editor.setContents(guide.description);
    }
  }, [guide.description]);

  return (
    <SunEditor
      ref={editorRef}
      autoFocus={true}
      onChange={handleEditorChange}
      setOptions={toolbarOptions}
    />
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:33:14