如何在Gutenberg"手动"插入一个块?

Bas*_* Ho 4 javascript wordpress wordpress-gutenberg gutenberg-blocks

古登堡的API是安静的模糊,我想不出如何创建和块附加到一个职位.

我发现wp.blocks.createBlock('core/paragraph', {content: "blabla"});它返回一个漂亮的块对象,但不会将任何内容附加到帖子中.

我想通过单击按钮插入一个包含一些自定义内容的简单段落.

小智 8

var content = "Test content";
var el = wp.element.createElement;
var name = 'core/paragraph';
// var name = 'core/html';
insertedBlock = wp.blocks.createBlock(name, {
    content: content,
});
wp.data.dispatch('core/editor').insertBlocks(insertedBlock);
Run Code Online (Sandbox Code Playgroud)


Eri*_*ica 5

也许这个源代码可以帮助https://github.com/WordPress/gutenberg/blob/master/editor/components/inserter/index.js

\n\n

查看文件末尾的部分

\n\n
onInsertBlock: ( item ) => {\n        const { insertionPoint, selectedBlock } = ownProps;\n        const { index, rootUID, layout } = insertionPoint;\n        const { name, initialAttributes } = item;\n        const insertedBlock = createBlock( name, { ...initialAttributes, layout } );\n        if ( selectedBlock && isUnmodifiedDefaultBlock( selectedBlock ) ) {\n            return dispatch( \'core/editor\' ).replaceBlocks( selectedBlock.uid, insertedBlock );\n        }\n        return dispatch( \'core/editor\' ).insertBlock( insertedBlock, index, rootUID );\n    },\n
Run Code Online (Sandbox Code Playgroud)\n\n

更具体

\n\n
return dispatch( \'core/editor\' ).insertBlock( insertedBlock, index, rootUID );\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望有助于解决你的问题,因为它\xc2\xb4s做你想要实现的同样的事情

\n