我想制作一个wordpress(gutenberg)块,您可以在其中输入文本。输出将是引导程序中可扩展的文本字段。 https://getbootstrap.com/docs/4.0/components/collapse/
wordpress文档示例不起作用。 因此,我使用了教程中的一些php和javascript代码来尝试首次制作wordpress块:
Functions.php
function mdlr_editable_block_example_backend_enqueue() {
wp_enqueue_script(
'mdlr-editable-block-example-backend-script', // Unique handle.
get_template_directory_uri() . '/assets/js/block.js', // Block.js: We register the block here.
array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ), // Dependencies, defined above.
filemtime( plugin_dir_path( __FILE__ ) . 'block.js' ) // filemtime — Gets file modification time.
);
block.js
/**
* Editable Block Example
*
* https://github.com/modularwp/gutenberg-block-editable-example
*/
( function() {
var __ = wp.i18n.__; // The __() function for internationalization.
var createElement = wp.element.createElement; // The wp.element.createElement() function to create elements.
var registerBlockType = wp.blocks.registerBlockType; // The registerBlockType() function to register blocks.
var RichText = wp.editor.RichText; // For creating editable elements.
/**
* Register block
*
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} Block itself, if registered successfully,
* otherwise "undefined".
*/
registerBlockType(
'mdlr/editable-block-example', // Block name. Must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
{
title: __( 'Editable Block Example' ), // Block title. __() function allows for internationalization.
icon: 'unlock', // Block icon from Dashicons. https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category. Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
attributes: {
content: {
type: 'string',
default: 'Editable block content...',
},
},
// Defines the block within the editor.
edit: function( props ) {
var content = props.attributes.content;
var focus = props.focus;
function onChangeContent( updatedContent ) {
props.setAttributes( { content: updatedContent } );
}
return createElement(
RichText,
{
tagName: 'p',
className: props.className,
value: content,
onChange: onChangeContent,
focus: focus,
onFocus: props.setFocus
},
);
},
// Defines the saved block.
save: function( props ) {
var content = props.attributes.content;
return createElement( RichText.Content,
{
'tagName': 'div',
'value': content
}
);
},
}
);
})();
此代码有效。我做的第一个测试是更改内容:
save: function( props ) {
var content = props.attributes.content;
return '<div> test </div>';
}
我尝试过:
save: function( props ) {
var content = props.attributes.content;
return <div> test </div>;
我似乎正在丢失或误解了某些内容。
有人可以指出我正确的方向吗?
答案 0 :(得分:0)
您不能直接从保存或编辑功能返回html元素。转到https://babeljs.io/repl,选择2015,然后将html标记放入框内进行转换。您可以有一个根元素,因此应将整个内容包装在单个htlm元素中。检出react元素,因为用于保存和编辑的返回元素应该是有效的react元素。