要扩展现有功能,您可以使用
compose
编辑.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);
/**
* 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
...
});