古腾堡Wordpress:扩展核心块

时间:2018-12-08 05:01:31

标签: wordpress wordpress-gutenberg gutenberg-blocks

我正在尝试将填充检查器控件添加到新的Gutenberg Wordpress编辑器的所有核心模块中。我已经在编辑器上创建了控件,现在尝试将这种样式应用于块元素本身。

但是我在块上不断出现This block contains unexpected or invalid content.错误。有人可以帮我解决我究竟在做什么吗?

  var paddingEditor = wp.compose.createHigherOrderComponent(function(
    BlockEdit
  ) {
    return function(props) {
      var padding = props.attributes.padding || 0;
      handleChange = name => newValue => {
        if (props) {
          props.setAttributes({ [name]: newValue });
        }
      };
      return el(
        Fragment,
        {},
        el(BlockEdit, props),
        el(
          editor.InspectorControls,
          {},
          el(
            components.PanelBody,
            {
              title: "Padding",
              className: "",
              initialOpen: false
            },
            el("p", {}, "Padding"),
            el(components.TextControl, {
              value: padding,
              onChange: this.handleChange("padding")
            })
          )
        )
      );
    };
  },
  "paddingStyle");

  wp.hooks.addFilter(
    "editor.BlockEdit",
    "my-plugin/padding-style",
    paddingStyle
  );

  function AddPaddingAttribute(element, blockType, attributes) {
    Object.assign(blockType.attributes, {
      padding: {
        type: "string"
      }
    });

    return element;
  }

  wp.hooks.addFilter(
    "blocks.getSaveElement",
    "my-plugin/add-padding-attr",
    AddPaddingAttribute
  );

  function AddPaddingStyle(props, blockType, attributes) {
    if (attributes.padding) {
      props.style = lodash.assign(props.style, { padding: attributes.padding });
    }
    return props;
  }

  wp.hooks.addFilter(
    "blocks.getSaveContent.extraProps",
    "my-plugin/add-background-color-style",
    AddPaddingStyle
  );

PHP

function register_block_extensions(){

    wp_register_script(
        'extend-blocks', // Handle.
        get_template_directory_uri() . '/js/extend-blocks.js',
        array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-editor' )
    );
    wp_enqueue_script( 'extend-blocks' );

  }
  add_action('enqueue_block_editor_assets', 'register_block_extensions');

1 个答案:

答案 0 :(得分:0)

您的编辑器。BlockEdit看起来正确,但是对我来说解析旧语法很难。假设它是正确的,则需要用以下代码替换blocks.getSaveElement:

function AddPaddingAttribute(props) {
  if (props.attributes) { // Some modules don't have attributes
    props.attributes = Object.assign(
      props.attributes,
      {
        padding: {}
      }
    );
  }
  return props;
}
wp.hooks.addFilter(
  'blocks.registerBlockType',
  'my-plugin/add-padding-attr',
  AddPaddingAttribute
);

然后将blocks.getSaveContent.extraProps修改为此:

function AddPaddingStyle(props, blockType, attributes) {
  return Object.assign(
    props,
    {
      style: {
        padding: attributes.padding
      }
    }
  );
}
wp.hooks.addFilter(
  "blocks.getSaveContent.extraProps",
  "my-plugin/add-background-color-style",
  AddPaddingStyle
);