首页 > 解决方案 > 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),

如何修改我的版本以适应这个新代码?有没有人有另一种兼容方式的示例?

标签: reactjswordpresswordpress-gutenberg

解决方案


要扩展现有功能,您可以利用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
...
});

推荐阅读