我正在尝试用下拉列表创建一个古腾堡动态块。我已经完成了块的创建,并在前端使用选定的下拉值渲染块。
编辑帖子时,如何设置使用上一个值选择的下拉列表?
我尝试使用访问属性值props.attributes
, 但是undefined
block.js
const { __ } = wp.i18n;
const { registerBlockType, RichText } = wp.blocks;
registerBlockType( \'gut/new-block\', {
title: __( \'new-block - Test\' ),
category: \'common\',
attributes: {
category_id: {
type: \'number\'
}
},
edit: function( props ) {
const { attributes: { category_id }, setAttributes } = props;
function setCategory( event ) {
const selected = event.target.querySelector( \'option:checked\' );
setAttributes( { category_id: selected.value } );
event.preventDefault();
}
return (
<div className={ props.className }>
<select value={ category_id } onChange={ setCategory }>
<option value="120">Animals</option>
<option value="350">Architecture</option>
<option value="700">Nature</option>
<option value="800">People</option>
<option value="432">Tech</option>
</select>
</div>
);
},
save ( props ) {
return null
},
});
PHP
function gut_my_new_block() {
wp_register_script(
\'gut-my-new-block\',
plugins_url( \'new-block/dist/blocks.build.js\', __FILE__ ),
array( \'wp-blocks\', \'wp-element\' )
);
register_block_type( \'gut/new-block\', array(
\'render_callback\' => \'gut_render_block_my_newblock\',
\'editor_script\' => \'gut-my-new-block\',
) );
}
add_action( \'init\', \'gut_my_new_block\' );
function gut_render_block_my_newblock($params) {
return \'<h3>selected category \'.$params[\'category_id\'].\'</h3>\';
}