1

我正在尝试向新的 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');
4

1 回答 1

0

您的 editor.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
);
于 2019-01-15T15:56:01.300 回答