首页 > 解决方案 > Wordpress 古腾堡块

问题描述

我有一个自定义块的问题,当我重新加载版本页面时它会向我发送一个错误。

我不明白问题是什么。关于误差,实际和预期是相同的。

这里的错误:

块验证:namespace/nottomiss({object})的块验证失败。

预期的:

<div class="wp-block-utopiales-nottomiss"><p>label test</p><p>label test</p></div>

实际的:

<div class="wp-block-utopiales-nottomiss"><p>label test</p><p>title test</p></div>

这是我的代码:

const { registerBlockType } = wp.blocks;
const { __ } = wp.i18n;
const { PanelBody, TextControl } = wp.components;
const { BlockControls, InspectorControls, RichText } = wp.editor;
const { createElement, Fragment } = wp.element

registerBlockType( 'namespace/nottomiss', {
    title: __( 'Nottomiss' ),
    description: __('My description'),
    icon: 'star-filled',
    category: 'widgets',
    supports: { align: true, alignWide: true },
    attributes: {
        label: {
            type: 'string',
            source: 'html',
            selector: 'p',
        },
    title: {
        type: 'string',
        source: 'html',
        selector: 'p',
    },
},
edit: function( props ) {
    const { label, title } = props.attributes;

    function onChangeLabel( newLabel ) {
        props.setAttributes( { label: newLabel } );
    }

    function onChangeTitle( newTitle ) {
        props.setAttributes( { title: newTitle } );
    }

    return (
        <Fragment>
            <BlockControls>
            </BlockControls>
            <InspectorControls>
                <PanelBody title={ __( 'List' ) }>
                </PanelBody>
            </InspectorControls>
            <RichText
                identifier="label"
                tagName="p"
                placeholder=""
                value={ label }
                onChange={ onChangeLabel }
            />
            <RichText
                identifier="title"
                tagName="p"
                placeholder=""
                value={ title }
                onChange={ onChangeTitle }
            />
        </Fragment>
    );
},
save: function( props ) {
    const { label, title } = props.attributes;

    return (
        <div>
            <RichText.Content
                tagName="p"
                value={ label }
            />
            <RichText.Content
                tagName="p"
                value={ title }
            />
        </div>
    );
},
} );

提前感谢您的回答,

标签: wordpresswordpress-gutenberggutenberg-blocks

解决方案


选择器是编辑器从保存的 html 中提取数据的方式,目前您的选择器并未针对内容。您可以将选择器更改为以下内容:

attributes: {
  label: {
    type: 'string',
    source: 'html',
    selector: '.label'
  },
  title: {
    type: 'string',
    source: 'html',
    selector: '.title'
  }
}

您可以将保存功能更改为:

save: function(props) {
  const { label, title } = props.attributes

  return (
    <div>
      <div className="label">
        <RichText.Content
          value={ label }
        />
      </div>
      <div className="title">
        <RichText.Content
          value={ title }
        />
      </div>
    </div>
  )
}

推荐阅读