Editor.js无法插入块报错:Uncaught TypeError问题求助
Editor.js 调用
blocks.insert时报错:Cannot read properties of undefined (reading 'insert') 问题原因
EditorJS的初始化是异步操作,你在实例化编辑器后立即调用editor.blocks.insert,此时编辑器还未完成初始化流程,editor.blocks属性还未被赋值,因此会抛出undefined相关的错误。
解决方案
使用EditorJS提供的onReady回调函数,确保在编辑器完全初始化完成后,再执行添加新块的操作。同时注意blocks.insert的正确调用方式:
修正后的完整代码
<html> <head> <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@2.30.6/dist/editorjs.umd.js" type="text/javascript"></script> </head> <body> <div id="editorjs" class="editor-holder"></div> <script> var editor = new EditorJS({ holder: 'editorjs', autofocus: true, data: { "time": 1550476186479, "blocks": [{ type: 'paragraph', data: { text: 'Hello world' } }] }, // 编辑器初始化完成后触发的回调 onReady: function() { const newBlock = { type: 'paragraph', data: { text: 'Hello world' } }; // 两种调用方式都有效: // 方式1:直接传入完整的块对象 editor.blocks.insert(newBlock); // 方式2:分开传入块类型和数据 // editor.blocks.insert(newBlock.type, newBlock.data); } }); </script> </body> </html>
其他尝试写法的问题说明
editor.configuration.data.blocks.push(newBlock):直接修改配置中的数据不会触发编辑器的视图更新,新添加的块不会被渲染到页面上。editor.api.blocks.insert(newBlock):EditorJS实例中不存在api属性,操作块的正确入口是editor.blocks。
内容的提问来源于stack exchange,提问作者Pawan Valluri
相关产品推荐
相关产品推荐

