代码之家  ›  专栏  ›  技术社区  ›  fightstarr20

古腾堡反应-努力使用

  •  0
  • fightstarr20  · 技术社区  · 4 年前

    我目前正在使用Gutenberg构建一个自定义块,我通常使用这样的save。。。。

    edit({attributes, setAttributes}) {
    
        /* Set Constants */
        const {
            mytitle,
            mycontent
        } = attributes;
    
        function ontitleChange(newTitle) {
            setAttributes({ title: newTitle});
        }
    
        return ([
             <TextControl 
                value={title}
                label="Title"
                onChange={(value) => {ontitleChange}
            />
        ])
    
    },
    

    这是伟大的工作,但现在我正试图添加一个媒体上传,使用与选择,所有的例子,我看到使用这种格式。。。。

    edit: withSelect((select, props) => {
        return { media: props.attributes.mediaId ? select('core').getMedia(props.attributes.mediaId) : undefined };
    })(BlockEdit),
    

    如何修改版本以适应新代码?有人用另一种兼容的方式写过一个例子吗?

    0 回复  |  直到 4 年前
        1
  •  0
  •   S.Walsh    4 年前

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