我试图用下拉列表创建一个 Gutenberg 动态块。我已完成块创建并在前端使用选定的下拉值呈现块。
编辑帖子时如何设置使用先前值选择的下拉列表?
我尝试使用 props.attributes 访问属性值,但得到undefined
块.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>';
}