reactjs - Gutenberg React - 努力使用 withSelect
问题描述
我目前正在使用 Gutenberg 构建一个自定义块,我通常使用这样的保存....
edit({attributes, setAttributes}) {
/* Set Constants */
const {
mytitle,
mycontent
} = attributes;
function ontitleChange(newTitle) {
setAttributes({ title: newTitle});
}
return ([
<TextControl
value={title}
label="Title"
onChange={(value) => {ontitleChange}
/>
])
},
这很好用,但现在我正在尝试添加使用 withSelect 的媒体上传,我见过的所有示例都以这种格式使用它......
edit: withSelect((select, props) => {
return { media: props.attributes.mediaId ? select('core').getMedia(props.attributes.mediaId) : undefined };
})(BlockEdit),
如何修改我的版本以适应这个新代码?有没有人有另一种兼容方式的示例?
解决方案
要扩展现有功能,您可以利用compose包装现有的编辑功能并创建增强组件。为了使您的代码基本保持不变并且更易于管理,请将您拥有的内容作为您的 edit() 函数并创建一个新文件:
编辑.js
import { withSelect } from '@wordpress/data';
import { compose } from '@wordpress/compose';
import { TextControl } from '@wordpress/components';
export function Edit({ attributes, setAttributes, media }) {
console.log(media); // media contains the returned value of applyWithSelect
/* Set Constants */
const {
title,
content
} = attributes;
// nb: removed function ontitleChange() in favour of directly calling setAttributes()
return (
<TextControl
value={title}
label="Title"
onChange={(value) => setAttributes({ title: value })}
/>
)
}
const applyWithSelect = withSelect((select, props) => {
// media is the name of the returned value
return { media: props.attributes.mediaId ? select('core').getMedia(props.attributes.mediaId) : undefined };
});
/**
* Use compose to return the result of withSelect to Edit({...})
* @see https://developer.wordpress.org/block-editor/packages/packages-compose/
*/
export default compose(
applyWithSelect,
)(Edit);
index.js
/**
* Internal dependencies
*/
import Edit from './edit';
registerBlockType('myproject/blockname', {
...
attributes: {
mediaId: {
type: 'number',
... // other props as needed
},
title: {
type: 'string',
... // other props as needed
},
content: {
type: 'string',
... // other props as needed
}
edit: Edit, // this is now the name of exported component from edit.js
...
});
推荐阅读
- r - 如何制作包含大量数据的热图?
- python - ansible 错误:从版本导入 VERSION\nImportError: No module named version\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
- web-services - 从 Oracle 触发器调用 Web 服务
- angularjs - Ionic 2 中具有多个字段的条码扫描器
- angularjs - AngularJS - 客户端 MVC - 在目录结构中放置“模型”的位置
- jekyll - 包括来自另一个 MD 文件的前事
- ruby-on-rails - 地理编码器 - 如何使用多点附近查询?
- javascript - 如何在 react-native 中从 AsyncStorage 中删除特定项目?
- python - django 扩展隐藏前后导入
- javascript - 请求花费的时间太长了~1s Node Express API(TTFB 问题)