我正在尝试为我的SVG linearGradient元素分配一个唯一的ID,这是针对我正在工作的自定义古腾堡块,基本上我需要访问(或生成(一个唯一的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 })
}
如您所见,我正在尝试将实例 ID 分配给一个属性,以便我可以使用 props.attributes.id 将其访问到 SAVE 和 EDIT 函数中
感谢您的任何帮助。
要在古腾堡Edit
和Save
方法中获取唯一 ID,您可以使用在编辑和保存方法props
内部提供的clientId
Props。
例:
第一个设置属性:
attributes: {
blockId: {
type: 'string'
}
}
内部编辑方法
edit: function( props ) {
const { attributes, setAttributes, clientId } = props;
const { blockId } = attributes;
if ( ! blockId ) {
setAttributes( { blockId: clientId } );
}
}
从WP 5.8开始,您需要用useEffect
包装函数调用。
edit: function( props ) {
const { attributes, setAttributes, clientId } = props;
const { blockId } = attributes;
React.useEffect( () => {
if ( ! blockId ) {
setAttributes( { blockId: clientId } );
}
}, [] );
}
内部保存方法
save: function( props ) {
const { attributes } = props;
const { blockId } = attributes;
// So here `blockId` attribute will have a unique ID
}
希望对您有所帮助!