reactjs - 更改的属性不随 Wordpress 块挥动
问题描述
我在插件中有一个相当简单的块,使用npx @wordpress/create-block pn-DisplayBlocks
. block.json 中的属性是:
(代码根据下面的修复进行了更改)
"attributes": {
"pid": {
"type": "text",
"default": "444"
}
}
save.js 是:
import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
export default function Save( {attributes} ) {
console.log( "SAVING", attributes )
return (
<p { ...useBlockProps.save() }>
{ __( 'Pn Image – hello from the saved content! ' + attributes.pid, 'pn-image' ) }
</p>
);
}
和 edit.js 是:
import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
import './editor.scss';
import { __experimentalNumberControl as NumberControl } from '@wordpress/components';
export default function Edit( {attributes, setAttributes} ) {
console.log( "pid", attributes.pid )
return (
<p { ...useBlockProps() }>
{
__( 'Pn Image – hello from the editor! ' + attributes.pid, 'pn-image' )
}
<NumberControl
label="PID"
isShiftStepEnabled={ true }
onChange={ value => { setAttributes( {pid: value})} }
shiftStep={ 10 }
value={ attributes.pid }
/>
</p>
);
}
NumberControl 值在更改时使用正确的数字值更新 pid 和块,一切正常,但是如果我预览页面,我会看到 pid 的默认值显示,而不是我刚刚更改的那个。如果我更新页面以保存它,则相同;console.log 显示新的 pid 值,但当重新加载到编辑页面时,pid 恢复为默认值。也许我盯着太用力了,但对于我的生活,我看不出有什么问题。另外,我对此很陌生,所以我可能会做一些愚蠢的事情。
从 index.js 中的 registerBlockType 调用保存和编辑:
import { registerBlockType } from '@wordpress/blocks';
import './style.scss';
import Edit from './edit';
import Save from './save';
registerBlockType( 'pn-displayblocks/pn-image', {
edit: Edit,
save: Save,
} );
block.json 中的属性:
{
"apiVersion": 2,
"name": "pn-displayblocks/pn-image",
"version": "0.1.0",
"title": "Pn Image",
"category": "widgets",
"icon": "smiley",
"description": "Example block written with ESNext standard and JSX support – build step required.",
"supports": {
"html": false
},
"textdomain": "pn-displayblocks",
"editorScript": "file:./build/index.js",
"editorStyle": "file:./build/index.css",
"style": "file:./build/style-index.css",
"attributes": {
"pid": {
"type": "text",
"default": "444"
}
}
}
解决方案
您是否尝试将属性存储在 block 的注释中?
根据文档古腾堡:
The available source values are:
– (no value) – when no source is specified then data is stored in the block’s comment delimiter.
– attribute – data is stored in an HTML element attribute.
– text – data is stored in HTML text.
– html – data is stored in HTML. This is typically used by RichText.
– query – data is stored as an array of objects.
– meta – data is stored in post meta (deprecated)
你可以试试吗?
"pid": {
"type": "text",
"default": "444"
}
推荐阅读
- arrays - 在 Array 中找到一个字母(来自一个 Array),然后使用索引从另一个 Array 中获取一个值
- java - IllegalBlockSizeException:使用填充密码解密时输入长度必须是 8 的倍数?
- javascript - React:处理事件 - 参数可见性
- verilog - 如何理解verilog中的阻塞和非阻塞语句?
- r - 使用 purrr 堆叠嵌套的数据帧列表
- python - 使用 datetime.strftime 并使用 timedelta 将其导出
- python - 重新排序整数的数字
- javascript - React 路由器渲染两个子组件而不是一个
- java - 如何在方法之前和之后从带有参数的函数在方言上注册函数?
- c# - 使用资源更改 Web 表单母版页上的控制文本