我是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
和前端框架(如React.js(实际上是库而非框架)和Angular)的组合不被认为是一个很好的组合,因此建议不要使用它。
前端框架维护每个组件的状态,如果我们通过jQuery或使用JS访问节点来更改该组件,那么这些状态不会在框架中更新。对于更新状态框架在React中提供自己的方法,方法是setState(obj)
,而在Gutenberg中,方法是setAttributes(obj)
,它实际上是React.js setState()
的包装器。
以下是我建议您制作此组件的一些建议(考虑到这不是服务器端块)。
JSX
而不是JavaScript的ES5
语法。 WordPress文档默认显示ES5
的示例代码,但有一个选项卡将其更改为JSX
。core/gallery
块相同(在选择多个图像时显示在底部)。attributes
中添加一个新对象,该对象也出现在前端,从前端我将值添加到此新块中。 Gutenberg <RichText/>
组件对于处理文本内容非常有帮助。onChange
上陈述<RichText/>
事件。为了更好地了解古腾堡生态系统,我建议您熟悉以下事项:
setState()
或setAttributes()
更新状态,而不是直接访问this.props.attributes
or this.props.state
ComponentDidMount
生命周期中获取数据,然后更新状态。可以通过任何API甚至WordPress REST API获取数据。