我在 Wordpress 项目中创建自定义古腾堡块时遇到问题。我为此使用 @wordpress/create-block 库。
我遇到的问题是在保存块后尝试编辑该块时。我正在创建一个块来使用 RichText 组件添加简单的引用和作者。这是我的 edit.js 文件中的 edit 函数
export default function Edit({ attributes, setAttributes }) {
const blockProps = useBlockProps()
const { quote, author } = attributes
const onChangeQuote = newQuote => setAttributes({ quote: newQuote})
const onChangeAuthor = newAuthor => setAttributes({ author: newAuthor})
return (
<div { ...blockProps }>
<RichText
tagName="div"
onChange={ onChangeQuote }
value={quote}
placeholder={__( 'Add Quote' )}
className="quote"
/>
<RichText
tagName="div"
onChange={ onChangeAuthor }
value={author}
placeholder={__( 'Add Author' )}
className="author"
/>
</div>
);
}
这只是一个保存引用和作者的功能。
这是我的 save.js 文件中的 save 函数
export default function save({ attributes }) {
const blockProps = useBlockProps.save()
const { quote, author } = attributes
return (
<div { ...blockProps }>
<div className="quote">{ quote }</div>
<div className="author">{ author }</div>
</div>
);
}
这就是该块保存在我的数据库中的方式
<!-- wp:pull-quote-test/pull-quote-test --><div class="wp-block-pull-quote-test-pull-quote-test"><div class="quote">Test</div><div class="author">author</div><div class="test">Test</div></div><!-- /wp:pull-quote-test/pull-quote-test -->
所以到目前为止一切都工作正常,问题是当尝试再次编辑帖子时,如果我重新加载页面,则会收到此错误消息
不知何故,保存函数返回的 HTML 与数据库中保存的 HTML 不同。这是返回对象
您可以看到变量是串联的,因此 WordPress 表示该块包含无效信息。
要添加更多信息,这是我为组件添加的 block.js 属性
"attributes": {
"quote": {
"type": "string",
"source": "text",
"selector": "div"
},
"author": {
"type": "string",
"source": "text",
"selector": "div"
}
}
如果有人知道可能导致此问题的原因以及如何解决它,我将不胜感激。
我怀疑问题是你的属性选择器不明确。 尝试更具体一些
"attributes": {
"quote": {
"type": "string",
"source": "text",
"selector": ".quote"
},
"author": {
"type": "string",
"source": "text",
"selector": ".author"
}
}