您可以通过选择和调度挂钩将数据传递给子级。因此,可以使用继承属性设置子块,并在父块上的设置更改时更新该属性。
Parent Block
导入依赖项
import { dispatch, select } from "@wordpress/data";
您的编辑功能可能如下所示:
edit({ attributes, className, setAttributes, clientId }) {
const { headerStyle } = attributes;
const updateHeaderStyle = function( value ) {
setAttributes({ headerStyle: value });
// Update the child block\'s attributes
var children = select(\'core/block-editor\').getBlocksByClientId(clientId)[0].innerBlocks;
children.forEach(function(child){
dispatch(\'core/block-editor\').updateBlockAttributes(child.clientId, {inheritedHeaderStyle: value})
});
}
return (
<>
<InspectorControls>
<PanelBody>
<RadioControl
label="Section Header Style"
selected = {headerStyle}
options = { [
{ label: \'h2\', value: \'h2\' },
{ label: \'h3\', value: \'h3\' },
{ label: \'h4\', value: \'h4\' },
{ label: \'h5\', value: \'h5\' },
{ label: \'h6\', value: \'h6\' },
]}
onChange= {updateHeaderStyle}
/>
</PanelBody>
</InspectorControls>
<InnerBlocks
...
/>
<>
);
}
Child Block
上述函数将在更改时更新,但在子块的编辑函数中,您可以获取父属性并在未定义的情况下进行设置。。。
if (!inheritedHeaderStyle) {
var parent = select(\'core/block-editor\').getBlockParents(clientId);
const parentAtts = select(\'core/block-editor\').getBlockAttributes(parent);
setAttributes( { inheritedHeaderStyle: parentAtts.headerStyle } )
}