我无法将“ InnerBlocks”的模板设置为变量/属性。我可以设置一个模板并使用它,而不会出现问题,但是我最终希望有一个包含3个不同模板的下拉菜单,因此我希望能够将模板设置为特定的属性。
看看我的编辑功能,我尝试过template={dashboardStyle}
和template={ {dashboardStyle} }
,但似乎都没有用。
import './style.scss';
import './editor.scss';
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText, InspectorControls, InnerBlocks } = wp.editor;
const dashboard2x2 = [
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
];
const dashboard3x3 = [
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
['wpress-blocks/dashboard-item'],
];
registerBlockType('wpress-blocks/dashboard', {
title: __('dashboard'), // Block title
icon: 'dashboard', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed
keywords: [
__('block'),
__('dashboard')
],
attributes:{
dashboardStyle: {
type: 'string',
default: 'dashboard3x3',
},
},
edit: function (props) {
const { attributes, className } = props
const dashboardStyle = attributes.dashboardStyle
return (
<div className={className}>
<InnerBlocks
template={dashboard3x3}
/>
</div>
);
},
save: function (props) {
return (
<div>
<InnerBlocks.Content />
</div>
);
},
});
代码按原样正确运行,但是当我尝试使用属性dasbhoardStyle
代替显式命名模板(以列出的方式)时,出现控制台错误n is undefined
。
我认为我的语法已关闭,但是我找不到能够执行相同操作的示例,并且我在文档中也没有找到有关如何执行此操作的任何内容,因此我只是猜到到目前为止我已经尝试了什么。任何想法都将不胜感激。
答案 0 :(得分:0)
万一其他人找到了这个并且想知道同一件事,这就是我想出的解决方案:
首先,我在名为“模板”的数组中定义了模板样式
const templates = {
dashboard2x2: [
['wpress-blocks/dashboard-item2x2', { className: 'col-md-6'} ],
['wpress-blocks/dashboard-item2x2', { className: 'col-md-6'} ],
['wpress-blocks/dashboard-item2x2', { className: 'col-md-6'} ],
['wpress-blocks/dashboard-item2x2', { className: 'col-md-6'} ],
],
dashboard3x2: [
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
['wpress-blocks/dashboard-item3x2', { className: 'col-md-4'} ],
]
}
然后将其添加到我的编辑功能中:
const activeTemplate = templates[attributes.dashboardStyle];
添加了一个下拉菜单,以允许我在样式之间进行选择:
<InspectorControls>
<SelectControl
label={ __( 'Select Dashboard Style' ) }
value={ attributes.dashboardStyle }
onChange={ ( dashboardStyle ) => { setAttributes( { dashboardStyle } ) } }
options={ [
{ value: 'dashboard2x2', label: '2 by 2' },
{ value: 'dashboard3x2', label: '3 by 2' },
] }
/>
</InspectorControls>
,然后将我的InnerBlocks更改为使用模板“ activeTemplate”,如下所示:
<InnerBlocks
template = { activeTemplate }
/>