使用EditorJS渲染已保存区块数据时超链接显示为标签文本问题
解决EditorJS超链接显示为HTML文本的问题
问题根源
- 初始数据中的HTML被转义成实体字符(比如
<a>而非<a>),EditorJS直接渲染为文本 - 官方Paragraph工具默认不允许解析HTML,会把所有内容当作纯文本处理
- 初始化时重复调用
render方法,可能导致数据加载冲突
解决步骤
1. 解码初始数据中的HTML实体
先把转义后的HTML字符串还原为原始HTML,确保EditorJS拿到的是可解析的内容:
// 解码HTML实体的工具函数 const decodeHtml = (str) => { const tempElement = document.createElement('div'); tempElement.innerHTML = str; return tempElement.textContent; }; // 处理传入EditorJS的初始数据 const processedData = { ...initialData, blocks: initialData.blocks.map(block => { if (block.type === 'paragraph' && block.data.text) { return { ...block, data: { ...block.data, text: decodeHtml(block.data.text) } }; } return block; }) };
2. 配置Paragraph工具允许HTML解析
使用官方Paragraph工具时,开启allowHTML配置项:
import Paragraph from '@editorjs/paragraph'; const tools = { paragraph: { class: Paragraph, config: { allowHTML: true // 核心配置:允许解析HTML内容 } }, // 其他工具保持不变 };
如果是自定义Paragraph工具,直接在render方法中使用innerHTML渲染内容:
class CustomParagraph { render() { const container = document.createElement('div'); container.className = this.api.styles.block; // 直接插入HTML而非纯文本 container.innerHTML = this.data.text || ''; return container; } save(blockElement) { return { text: blockElement.innerHTML }; } }
3. 移除重复的render调用
初始化EditorJS时已经通过data参数传入了初始数据,无需在useEffect中再次调用render,避免数据加载冲突:
// 修改Editor.tsx中的useEffect useEffect(() => { if (editorInstanceRef.current) { editorInstanceRef.current.isReady .then(() => { setIsEditorReady(true); onReady && onReady(); // 移除这里的render调用 }) .catch(error => console.error('编辑器就绪失败:', error)); } return () => { if (editorInstanceRef.current) { editorInstanceRef.current.isReady .then(() => { editorInstanceRef.current?.destroy(); editorInstanceRef.current = null; }) .catch(error => console.error('编辑器销毁失败:', error)); } }; }, [editorInstanceRef, onReady]); // 移除initialData依赖
验证效果
处理后,EditorJS会正确解析<a>标签并渲染为可点击的超链接,而非显示HTML文本。
内容的提问来源于stack exchange,提问作者Fery
相关产品推荐
相关产品推荐

