【问题标题】:Gutenberg: Dynamic Block - Show saved data in the editorGutenberg: Dynamic Block - 在编辑器中显示保存的数据
【发布时间】:2019-07-01 05:14:06
【问题描述】:

我正在尝试使用下拉列表创建 Gutenberg 动态块。我已经完成了块创建并在前端使用选定的下拉值渲染块。

编辑帖子时如何设置使用先前值选择的下拉菜单?

我尝试使用 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>';
}

【问题讨论】:

    标签: wordpress wordpress-rest-api wordpress-gutenberg gutenberg-blocks create-guten-block


    【解决方案1】:

    选择值保存为字符串,因此如果您将类型更改为“字符串”,它将起作用。或者你可以在保存之前解析Int() 或 Number() 值,然后在拉取值时返回toString()。

    【讨论】:

    • 我必须使用 Number() 函数转换数据。现在可以使用了
    猜你喜欢
    • 2023-02-13
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2018-08-19
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多