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>,而非<p>xxx</p>)。 - 如果数据被转义(出现
<、>等实体字符),需要解码为原始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 heimport 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
相关产品推荐
相关产品推荐

