Lea*_*erg 5 wordpress block reactjs wordpress-gutenberg
我正在尝试将唯一的 ID 分配到我的 SVG LinearGradient 元素中,这是针对我正在工作的自定义古腾堡块,基本上我需要访问(或生成)一个唯一的 id,以便我可以将其放入元素 HTML id 中范围。
我知道我们有一个主块 ID,我们可以使用 CSS 进行样式设置并创建锚点,但这对我想要实现的目标没有帮助。
我发现了这个https://developer.wordpress.org/block-editor/packages/packages-compose/#withInstanceId但我不明白如何使用它,文档没有给我简单的例子。
请按照我的块代码的一部分(这不起作用):
attributes: {
id: {
type: 'string',
default: withInstanceId(function({instanceId}){ return instanceId })
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我正在尝试将实例 ID 分配给属性,以便我可以使用 props.attributes.id 将其访问到 SAVE 和 EDIT 函数中
谢谢你的帮助。
Kis*_*ani 13
Edit要在古腾堡和方法中获取唯一的 ID,Save您可以使用编辑和保存方法clientId内部提供的 Props 。props
例子:
首先设置属性:
attributes: {
blockId: {
type: 'string'
}
}
Run Code Online (Sandbox Code Playgroud)
内部编辑方法
edit: function( props ) {
const { attributes, setAttributes, clientId } = props;
const { blockId } = attributes;
if ( ! blockId ) {
setAttributes( { blockId: clientId } );
}
}
Run Code Online (Sandbox Code Playgroud)
从 WP 5.8 开始,您需要用 包装函数调用useEffect。
edit: function( props ) {
const { attributes, setAttributes, clientId } = props;
const { blockId } = attributes;
React.useEffect( () => {
if ( ! blockId ) {
setAttributes( { blockId: clientId } );
}
}, [] );
}
Run Code Online (Sandbox Code Playgroud)
内部保存方法
save: function( props ) {
const { attributes } = props;
const { blockId } = attributes;
// So here `blockId` attribute will have a unique ID
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
7810 次 |
| 最近记录: |