我是Wordpress Gutenberg区块的新手。我创建了一个画廊插件,我希望用户能够通过从弹出窗口中选择所需的画廊来插入画廊简码。我使用jQuery text()函数成功从弹出窗口中插入了短代码,但不会保存内容。但是,当我输入一些文本时,一切正常。
这是我的古腾堡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
});
},
});
答案 0 :(得分:0)
jQuery
和前端框架(例如React.js(实际上是库而不是框架)和Angular)的组合被认为不是很好的组合,因此建议不要使用它。
前端框架维护每个组件的状态,如果我们通过jQuery或通过使用JS访问节点来更改该组件,则这些状态不会在框架中更新。为了更新状态,框架在React中提供了自己的方法,方法为setState(obj)
,而在古腾堡中,方法为setAttributes(obj)
,实际上是React.js setState()
的包装器。
以下是一些建议我建议您制作此组件的建议(考虑到这不是服务器端块)。
JSX
代替JavaScript的ES5
语法。 WordPress的
默认情况下,文档显示示例代码ES5
,但是有一个选项卡
将其更改为JSX
。core/gallery
块一样(选择多个图像时显示在底部)。attributes
中,该对象也出现在前端,然后从前端将值添加到该新块中。古腾堡<RichText/>
组件对于处理文本内容非常有帮助。onChange
上的<RichText/>
事件状态。为了更好地了解古腾堡生态系统,建议您熟悉以下内容:
setState()
或setAttributes()
更新状态,而不是直接访问this.props.attributes
或this.props.state
ComponentDidMount
生命周期中获取数据,然后更新状态。可以通过任何API甚至WordPress REST API提取数据。