admin管理员组文章数量:1327750
The WordPress block API for Gutenberg has a withInstanceId
package.
They say,
Some components need to generate a unique id for each instance. This could serve as suffixes to element ID's for example. Wrapping a component with withInstanceId provides a unique instanceId to serve this purpose.
and show an example:
/**
* WordPress dependencies
*/
import { withInstanceId } from '@wordpress/compose';
function MyCustomElement( { instanceId } ) {
return (
<div id={ `my-custom-element-${ instanceId }` }>
content
</div>
);
}
export default withInstanceId( MyCustomElement );
It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using export default withInstanceId( MyCustomElement )
will the entire component have a unique id?
The WordPress block API for Gutenberg has a withInstanceId
package.
They say,
Some components need to generate a unique id for each instance. This could serve as suffixes to element ID's for example. Wrapping a component with withInstanceId provides a unique instanceId to serve this purpose.
and show an example:
/**
* WordPress dependencies
*/
import { withInstanceId } from '@wordpress/compose';
function MyCustomElement( { instanceId } ) {
return (
<div id={ `my-custom-element-${ instanceId }` }>
content
</div>
);
}
export default withInstanceId( MyCustomElement );
It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using export default withInstanceId( MyCustomElement )
will the entire component have a unique id?
2 Answers
Reset to default 1The generated id
is added to the component's props. So it can be accessed through this.props.instanceId
inside the component.
In the example you posted it is being used to assign a unique id attribute to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an id
and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its id
to find it.
You could use clientId to uniquely identify the block. clientId is available in props.
Something like this..
export function EditBlock({clientId, setAttributes} ) {
// save clientId in attributes to make it available in Save
return (
<div id={ `my-custom-element-${ clientId }` }>
content
</div>
);
}
No need for HOC.
本文标签: block editorGutenberg withInstanceId When to use it
版权声明:本文标题:block editor - Gutenberg withInstanceId. When to use it? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742234143a2437761.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论