admin管理员组

文章数量:1287607

I am trying to save an attribute for a custom Gutenberg block. Call it contenttype.

This attribute is already predefined - for instance, "discussion"

In my code, I figured this would be straightforward.

Here is my list of attributes:

    attributes: {

        selectedPost: {
            type: 'number',
            default: 0,
        },
        contenttitle: {
            type: 'string',
            default: '',
        },
        contenttype: {
            type: 'string',
            default: 'discussion',
        },
        blockId: {
            type: 'string',
            default: '',
        },
    },

And here is where I set their values:

    onChangeSelectPost( value ) {
        // Find the post
        const post = this.state.posts.find( ( item ) => { return item.id == parseInt( value ) } );
        // Set the state
        this.setState( { selectedPost: parseInt( value ), post } );
        // Set the attributes
        this.props.setAttributes( {
            selectedPost: parseInt( value ),
            contenttitle: post.title.rendered,
            contenttype: 'discussion',
            blockId: this.props.clientId,
        });
    }

All is working fine, except that this contenttype just isn't showing up in the block's attributes. What I see in the database is

<!-- wp:cgb/block-my-block {"selectedPost":1071,"contenttitle":"Some Title","blockId":"8654cc3c-5k6d-47f4-8e22-97a0c3554567"} /-->

Am I doing something obviously wrong here?

thanks

--- Update: This seems to shed light on the problem:

So now I have it working if I specify default so some arbitrary string, like "blah". Oddly enough, it was not working when I had default:''. Here is how I know specify the default:

        contenttype: {
            type: 'string',
            default: 'discussion',
        },

And with the setAttributes call unchanged, that is

        this.props.setAttributes( {
            selectedPost: parseInt( value ),
            contenttitle: post.title.rendered,
            contenttype: 'discussion',
            blockId: this.props.clientId,
        });

all is working.

本文标签: Gutenberg BlocksSave a predefined text attribute