从其他古腾堡块获取信息和属性
Get information and attributes from other gutenberg blocks
是否可以从 registerBlockType 调用中的其他块获取信息,例如块属性?
例如如果我有一个以 InnerBlocks 作为内容的块,是否可以从该 InnerBlocks 内部的块获取属性,反之亦然?
是的,如果您在 Gutenberg 中管理自己的商店,这实际上是一个 Redux 商店,这是可能的。 @wordpress/data
建议将多个块的逻辑分别保存在它们自己的属性中(这就是它们是块的原因)。出于可重用性的目的,您可以制作可在不同块内使用的 React 组件,这样您的块的属性可以传递给 React 组件的 props。
您也可以使用 Block context 来实现。
在父块中,使用 providesContext
映射要在子块中使用的属性。因此,如果您想映射 recordId
属性,您的父块配置将如下所示:
registerBlockType('my-plugin/parent-block', {
// ...
attributes: {
recordId: {
type: 'number',
},
},
providesContext: {
'my-plugin/recordId': 'recordId',
},
// ...
}
然后子块可以通过将以下 useContext
行添加到您的子块配置来“使用”上下文:
registerBlockType('my-plugin/child-block', {
// ...
usesContext: ['my-plugin/recordId'],
// ...
}
在您的子块的 edit
和 save
方法中,您可以这样访问上下文:
registerBlockType('my-plugin/child-block', {
// ...
edit(props) {
const { context } = props;
const { "my-plugin/recordId": recordId } = context;
return (
<p>{ recordId }</p>
);
},
save(props) {
const { context } = props;
const { "my-plugin/recordId": recordId } = context;
return (
<p>{ recordId }</p>
);
}
// ...
}
是否可以从 registerBlockType 调用中的其他块获取信息,例如块属性?
例如如果我有一个以 InnerBlocks 作为内容的块,是否可以从该 InnerBlocks 内部的块获取属性,反之亦然?
是的,如果您在 Gutenberg 中管理自己的商店,这实际上是一个 Redux 商店,这是可能的。 @wordpress/data
建议将多个块的逻辑分别保存在它们自己的属性中(这就是它们是块的原因)。出于可重用性的目的,您可以制作可在不同块内使用的 React 组件,这样您的块的属性可以传递给 React 组件的 props。
您也可以使用 Block context 来实现。
在父块中,使用 providesContext
映射要在子块中使用的属性。因此,如果您想映射 recordId
属性,您的父块配置将如下所示:
registerBlockType('my-plugin/parent-block', {
// ...
attributes: {
recordId: {
type: 'number',
},
},
providesContext: {
'my-plugin/recordId': 'recordId',
},
// ...
}
然后子块可以通过将以下 useContext
行添加到您的子块配置来“使用”上下文:
registerBlockType('my-plugin/child-block', {
// ...
usesContext: ['my-plugin/recordId'],
// ...
}
在您的子块的 edit
和 save
方法中,您可以这样访问上下文:
registerBlockType('my-plugin/child-block', {
// ...
edit(props) {
const { context } = props;
const { "my-plugin/recordId": recordId } = context;
return (
<p>{ recordId }</p>
);
},
save(props) {
const { context } = props;
const { "my-plugin/recordId": recordId } = context;
return (
<p>{ recordId }</p>
);
}
// ...
}