注册块类型时,我们定义块结构在添加到编辑器时的状态。将块类型添加到编辑器后,我们就有了一个实际的块。
InnerBlock中的初始模板属性定义了添加(根)块类型时应添加哪些InnerBlock。添加后,道具将不起作用,因为已创建块。从那以后,我们需要修改特定的方块道具。
因此,在您的情况下,我们需要调度一个操作来修改存储中的块数据。我们可以通过wp.data.dispatch
, wp.data.withDispatch
或wp.data.useDispatch
. 我的建议是使用wp.data.useDispatch
它利用反应挂钩。
我们使用replaceInnerBlocks 作用此函数接受块clientId
和一组块。
这里的问题是,我们正在修改可能包含内容的块。我建议看看我们如何在this other answer. 我们要做的是获取现有的块,并在必要时将它们与通过编程创建的块合并(使用wp.blocks.createBlock
).
const { times } = lodash;
const { __ } = wp.i18n;
const { createBlock } = wp.blocks;
const { PanelBody, SelectControl } = wp.components;
const { InnerBlocks, InspectorControls } = wp.blockEditor;
const { useDispatch, useSelect } = wp.data;
const TEMPLATE = [
[
"myblocks/myblock",
{
a: "b",
c: "d"
}
]
];
export const settings = {
title: __("My Block", "mytextdomain"),
description: __("Description", "mytextdomain"),
keywords: [__("block")],
supports: {
align: false,
alignWide: false
},
attributes: {
a: {
type: "string"
},
c: {
type: "string"
}
},
edit: props => {
const { className, clientId } = props;
const { replaceInnerBlocks } = useDispatch("core/block-editor");
const { inner_blocks } = useSelect(select => ({
inner_blocks: select("core/block-editor").getBlocks(clientId)
}));
return (
<div className="myblock">
<InspectorControls>
<PanelBody title={__("Select", "mytextdomain")} initialOpen={true}>
<SelectControl
onChange={selected => {
let inner_blocks_new = inner_blocks;
/*
// If we need to add 3 new blocks
inner_blocks_new = [
...inner_blocks,
...times(3, () =>
createBlock("myblocks/myblock")
)
];
*/
/*
// If we need to remove blocks after the third one
inner_blocks_new = inner_blocks.slice(0, 3);
*/
replaceInnerBlocks(clientId, inner_blocks_new, false);
}}
label={__("Select Item", "mytextdomain")}
options={options}
/>
</PanelBody>
</InspectorControls>
<h1>{__("Some Title")}</h1>
<InnerBlocks
template={TEMPLATE}
allowedBlocks={["myblocks/myblock"]}
templateLock={false}
/>
</div>
);
},
save: () => null
};