React中自定义Editor.js区块:如何实现字号、字体样式等个性化设置?
可行,具体实现步骤如下
Editor.js本身支持自定义区块扩展,你要的字号、字体样式这类自定义设置完全可以通过扩展默认区块或者创建自定义区块来实现,下面是具体的实现思路和代码示例:
1. 自定义带样式设置的区块
默认的标题、文本区块没有样式配置面板,你需要基于默认区块进行修改,添加样式设置项。以自定义文本区块为例:
// CustomParagraph.js import Paragraph from '@editorjs/paragraph'; export default class CustomParagraph extends Paragraph { // 重写设置面板,添加字号、粗体选项 renderSettings() { const wrapper = document.createElement('div'); // 字号选择下拉框 const fontSizeSelect = document.createElement('select'); fontSizeSelect.innerHTML = ` <option value="14px">14px</option> <option value="16px" selected>16px</option> <option value="18px">18px</option> <option value="20px">20px</option> `; fontSizeSelect.addEventListener('change', (e) => { this._data.fontSize = e.target.value; this.api.rerender(); }); // 粗体切换按钮 const boldBtn = document.createElement('button'); boldBtn.textContent = 'B'; boldBtn.style.fontWeight = 'bold'; boldBtn.style.marginLeft = '8px'; boldBtn.addEventListener('click', () => { this._data.isBold = !this._data.isBold; this.api.rerender(); }); wrapper.appendChild(fontSizeSelect); wrapper.appendChild(boldBtn); return wrapper; } // 重写渲染逻辑,应用自定义样式 render() { const paragraph = super.render(); if (this._data.fontSize) { paragraph.style.fontSize = this._data.fontSize; } if (this._data.isBold) { paragraph.style.fontWeight = 'bold'; } return paragraph; } // 重写保存方法,确保样式数据被序列化 save(blockContent) { const baseData = super.save(blockContent); return { ...baseData, fontSize: this._data.fontSize || '16px', isBold: this._data.isBold || false }; } // 重写初始化方法,加载保存的样式数据 init(data) { super.init(data); this._data.fontSize = data.fontSize || '16px'; this._data.isBold = data.isBold || false; } }
2. 在React项目中集成自定义区块
在你的React组件里初始化Editor.js时,替换默认的paragraph为自定义区块:
import React, { useEffect, useRef } from 'react'; import EditorJS from '@editorjs/editorjs'; import CustomParagraph from './CustomParagraph'; // 如需自定义标题区块,同理创建CustomHeading后引入 export default function Editor() { const editorRef = useRef(null); useEffect(() => { if (!editorRef.current) { editorRef.current = new EditorJS({ holder: 'editorjs', tools: { paragraph: { class: CustomParagraph, inlineToolbar: true // 保留默认行内工具栏 }, // 自定义标题区块的配置示例 // heading: { // class: CustomHeading, // config: { // levels: [1,2,3,4], // defaultLevel: 2 // } // } }, // 加载已保存的数据(如有) // data: yourSavedEditorData }); } return () => { if (editorRef.current) { editorRef.current.destroy(); editorRef.current = null; } }; }, []); return <div id="editorjs" />; }
3. 扩展其他区块(比如标题)
标题区块的自定义逻辑和文本区块完全一致:复制@editorjs/heading的默认实现,重写renderSettings、render、save和init方法,添加字号、字体样式等配置项即可。
注意事项
- 样式设置项的UI可根据需求调整,比如添加字体家族选择器、斜体按钮等,只要能触发数据更新和重新渲染即可
- 确保保存的数据能正确序列化和反序列化,避免加载时样式丢失
- 如果需要全局统一管理样式,也可以将样式配置存入项目的状态管理工具(比如Redux),实现跨组件的样式同步
内容的提问来源于stack exchange,提问作者Nejd Bedoui
相关产品推荐
相关产品推荐

