Gutenberg向默认块添加自定义Metabox

时间:2018-07-24 作者:Bonttimo

是否可以在古腾堡的默认块中添加自定义元框?我需要向每个块添加一个用户定义的数据属性。然后,该数据属性将打印在包装器元素的前端。我还没有找到任何关于如何做到这一点的文档。

一幅图片来说明我的意思。enter image description here

2 个回复
SO网友:Alvaro

使用filters 我们可以修改块的道具和属性。首先,我们扩展属性以包括新属性:

const { addFilter } = wp.hooks;

// Register/add the new attribute.
const addExtraAttribute = props => {
    const attributes = {
        ...props.attributes,
        extra_attribute: {
            type: "string",
            default: "default_value"
        }
    };

    return { ...props, attributes };
};

addFilter(
    "blocks.registerBlockType",
    "my-plugin/extra-attribute",
    addExtraAttribute
);
然后,我们扩展块的编辑功能,以包含一个控件来修改属性:

const { addFilter } = wp.hooks;
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls } = wp.editor;
const { PanelBody, TextControl } = wp.components;

const addTextControl = createHigherOrderComponent(BlockEdit => {
    return props => {
        const { attributes, setAttributes } = props;
        return (
            <Fragment>
                <BlockEdit {...props} />
                <InspectorControls>
                    <PanelBody>
                        <TextControl
                            value={attributes.extra_attribute}
                            onChange={value => {
                                setAttributes({ extra_attribute: value });
                            }}
                        />
                    </PanelBody>
                </InspectorControls>
            </Fragment>
        );
    };
}, "withInspectorControl");

addFilter("editor.BlockEdit", "my-plugin/extra-attribute", addTextControl);
最后,我们扩展了分配给save函数的道具,并包括data attribute 添加属性值后:

const { addFilter } = wp.hooks;

// Add extra props. Here we assign an html
// data-attribute with the extra_attribute value.
const addExtraData = (props, block_type, attributes) => {
    return {
        ...props,
        "data-extra": attributes.extra_attribute
    }
};

addFilter(
    "blocks.getSaveContent.extraProps",
    "my-plugin/extra-attribute",
    addExtraData
);

SO网友:Harsh

对于古腾堡使用的自定义元框,请检查以下链接。https://wordpress.org/gutenberg/handbook/extensibility/meta-box/

结束