使用EditorJS开发笔记应用,如何统计每个区块的字符数?
问题
我正在使用EditorJS(块样式文本编辑器)开发一款笔记应用,想要统计每个区块的字符数。尝试在EditorJS的onChange方法中添加JavaScript代码,但未达到预期效果。当前的EditorJS配置代码如下:
const editor = new EditorJS({ holder: "editorjs", logLevel: "ERROR", data: editorData, onReady: () => { ejInstance.current = editor; }, onChange: async (api, event) => { console.log(event); let content = await editor.save(); setEditorData(content); let blockIndex = api.blocks.getCurrentBlockIndex(); let currentBlock = content.blocks.at(blockIndex - 1).data; setCount(currentBlock.text.length); }, autofocus: true, tools: { marker: Marker, unerline: Underline }, });
解决方案
问题原因
- 每次
onChange调用editor.save()属于冗余操作,异步执行还可能拿到非最新内容; getCurrentBlockIndex()返回的是0起始索引,用blockIndex - 1会错误定位到上一个块;- 未处理非文本类型块,一旦编辑器有其他工具块(如标题、列表),访问
text字段会报错。
修改后的代码
const editor = new EditorJS({ holder: "editorjs", logLevel: "ERROR", data: editorData, onReady: () => { ejInstance.current = editor; }, onChange: (api, event) => { // 直接从event中获取当前修改的块 const currentBlock = event.detail.block; // 仅处理含text字段的文本类块 if (currentBlock.data?.text !== undefined) { setCount(currentBlock.data.text.length); } else { // 非文本块可设为0或其他提示值 setCount(0); } // 同步最新内容到state(用api.saver.save更稳妥) api.saver.save().then(content => { setEditorData(content); }); }, autofocus: true, tools: { marker: Marker, unerline: Underline }, });
额外优化
- 若需统计所有块总字符数,可遍历数据计算:
const totalChars = editorData.blocks.reduce((total, block) => { return total + (block.data?.text?.length || 0); }, 0);
- 可给
setCount加防抖处理,避免输入时频繁触发状态更新,减少组件重渲染。
内容的提问来源于stack exchange,提问作者IshAsh
相关产品推荐
相关产品推荐

