我要给你介绍一下要点,因为我也很挣扎:)
首先导入InspectorControls
const { InspectorControls } = wp.editor;
然后导入组件,如
ColorPalette
const { ColorPalette } = wp.components;
为了保存状态,必须定义一个属性:
attributes: {
// To storage background colour of the div
background_color: {
type: \'string\',
default: \'red\', // Default value for newly added block
},
// To storage the complete style of the div that will be \'merged\' with the selected colors
block_style: {
selector: \'div\', // From tag a
source: \'attribute\', // binds an attribute of the tag
attribute: \'style\', // binds style of a: the dynamic colors
}
},
然后在
edit
作用定义
onChangeColorHandler
和一个变量,用于在
JSX, 因为你当然不能从css。
在return
part返回两个元素的数组[]
这个Inspector
和渲染的div
在编辑器中
edit: function( props ) {
var background_color = props.attributes.background_color // To bind button background color
// Style object for the button
// I created a style in JSX syntax to keep it here for
// the dynamic changes
var block_style = props.attributes.block_style // To bind the style of the button
block_style = {
backgroundColor: background_color,
color: \'#000\',
padding: \'14px 25px\',
fontSize: \'16px\',
}
//
// onChange event functions
//
function onChangeBgColor ( content ) {
props.setAttributes({background_color: content})
}
// Creates a <p class=\'wp-block-cgb-block-gtm-audio-block\'></p>.
return [
<InspectorControls>
<label class="blocks-base-control__label">background color</label>
<ColorPalette // Element Tag for Gutenberg standard colour selector
onChange={onChangeBgColor} // onChange event callback
/>
</InspectorControls>
,
<div className={ props.className } style={block_style}>
<p>— Hello from the backend.</p>
</div>
];
},
** 最后:**保存方法,只需为样式创建变量并提供渲染
div
该值的JSX样式。
save: function( props ) {
var block_style = {
backgroundColor: props.attributes.background_color
}
return (
<div style={block_style}>
<p>— Hello from the frontend.</p>
</div>
);
},
here is a complete gist of the file