简体   繁体   中英

WordPress Gutenberg-Block Editor component SelectControl: custom event prop

I am developing in Gutenberg-Blocks, WordPress.

I have some problems with customization of the SelectControl component. According to the reference handbook, the onChange prop is a function that receives the value of the new option that is being selected as input. The onChange event fires if the user actively make a change in the native select html element rendered by Blocks.

But if the user don't do any changes in the SelectControl component, no value is captured when the save function is fired (when a page or post get's published or saved as a draft).

There must be som kind of convention of implementing some other event, or even better, catch the default value from one of the options in the select element (even though no onChange event have been fired).

You can set a default value for the SelectControl via an attribute when you register your Block:

registerBlockType('my-blocks/custom-block', {
    ...
    attributes: {
        my_selection: {
            type: 'string',
            default: '100%',
            source: 'attribute',
            ...
        },
    }
...

Set the value of the SelectControl to the name of your attribute, the default value should exist in the options so it will be selected by default. The default value will be saved whenever the post is saved until the User makes a selection which updates the attributes value via onChange().

    <SelectControl
    label="Size"
    value={ attributes.my_selection }
    options={[
        { label: 'Big', value: '100%' },
        { label: 'Medium', value: '50%' },
        { label: 'Small', value: '25%' },
    ]}
    onChange={ (value) => setAttributes({ my_selection: value }) }
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM