Wordpress gutenberg块 - jquery生成的内容未保存

问题描述 投票:0回答:1

我是Wordpress Gutenberg块的新手。我创建了一个图库插件,我希望用户能够通过从弹出窗口中选择所需的图库来插入图库短代码。我使用jQuery text()函数从弹出窗口注入短代码但成功但内容不会被保存。但是,当我输入一些文本时,一切正常。

这是我的Gutenberg js:

var el = wp.element.createElement,
registerBlockType = wp.blocks.registerBlockType,
RichText = wp.editor.RichText,
blockStyle = { backgroundColor: '#0000cc', color: '#fff', padding: '1%', margin: '1%', border: 'none', boxShadow: '5px 5px 5px #000', cursor: 'pointer' };

registerBlockType( 'prtxgal/block', {
    title: 'Protex gallery',

    icon: 'images-alt',

    category: 'common',

    attributes: {
        content: {
            type: 'string',
            source: 'html',
            selector: 'div',
        }
    },

    edit: function(props) {
        var content = props.attributes.content;

        function onChangeContent( newContent ) {
            props.setAttributes( { content: newContent } );
        }

        return[ el(
            'button', { className: 'button add_prtxgal', /*style: blockStyle*/}, 'Choose gallery'
            ),
            el (RichText,
            {
                tagName: 'div',
                className: props.className,
                onChange: onChangeContent,
                value: content,
            }
            ),
        ];
    },

    save: function(props) {
        var content = props.attributes.content;

        return el( RichText.Content, {
            tagName: 'div',
            className: props.className,
            value: content
        });
    },
});
jquery wordpress save block wordpress-gutenberg
1个回答
1
投票

jQuery和前端框架(如React.js(实际上是库而非框架)和Angular)的组合不被认为是一个很好的组合,因此建议不要使用它。

原因

前端框架维护每个组件的状态,如果我们通过jQuery或使用JS访问节点来更改该组件,那么这些状态不会在框架中更新。对于更新状态框架在React中提供自己的方法,方法是setState(obj),而在Gutenberg中,方法是setAttributes(obj),它实际上是React.js setState()的包装器。

建议

以下是我建议您制作此组件的一些建议(考虑到这不是服务器端块)。

  1. 我将使用JSX而不是JavaScript的ES5语法。 WordPress文档默认显示ES5的示例代码,但有一个选项卡将其更改为JSX
  2. 我将显示添加项目按钮,其中添加了新的图库项目。该按钮的实现可以与core/gallery块相同(在选择多个图像时显示在底部)。
  3. 单击此Add Item将在我的attributes中添加一个新对象,该对象也出现在前端,从前端我将值添加到此新块中。 Gutenberg <RichText/>组件对于处理文本内容非常有帮助。
  4. 更新你在onChange上陈述<RichText/>事件。
  5. 类似地,可以实现更新和删除功能。
  6. 单击更新将获取全新内容并保存。

注意:

为了更好地了解古腾堡生态系统,我建议您熟悉以下事项:

  • ES6语法也称为ES2015。
  • React.js.React Documentation是非常好的资源。
  • Redux并不完全,只是如何使用纯函数逻辑更新对象(纯函数是不改变输入的函数)。 Some Examples from Redux Docs
  • 最后看看Gutenberg中存在的core blocks的实现。从简单的第一个开始,如段落,报价,列表等。
  • 始终使用setState()setAttributes()更新状态,而不是直接访问this.props.attributesor this.props.state

奖金

  • 您可以在React.js的ComponentDidMount生命周期中获取数据,然后更新状态。可以通过任何API甚至WordPress REST API获取数据。
© www.soinside.com 2019 - 2024. All rights reserved.