You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Gutenberg区块插件技术问询:后端JS交互前端仅输出HTML

问题1:编辑器端点击区块打开弹窗/侧边栏

实现弹窗(Modal)

在区块的edit函数中,用React状态管理控制弹窗显示,结合WordPress官方组件库的Modal实现交互:

import { useState } from '@wordpress/element';
import { Modal } from '@wordpress/components';

const MyBlock = {
  title: '可弹窗区块',
  category: 'widgets',
  edit: () => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    const openModal = () => setIsModalOpen(true);
    const closeModal = () => setIsModalOpen(false);

    return (
      <>
        <div onClick={openModal} style={{ padding: '20px', border: '1px dashed #ccc', cursor: 'pointer' }}>
          <h3>点击打开弹窗</h3>
        </div>
        {isModalOpen && (
          <Modal title="区块配置弹窗" onRequestClose={closeModal}>
            <p>这里可以添加表单、设置项等编辑器端交互内容</p>
            <button onClick={closeModal} style={{ marginTop: '16px' }}>关闭弹窗</button>
          </Modal>
        )}
      </>
    );
  },
  save: () => {
    // 无头架构下仅输出静态HTML
    return <h1>This is the frontend.</h1>;
  }
};

wp.blocks.registerBlockType('my-plugin/popup-block', MyBlock);
  • 用useState维护弹窗显示状态,点击区块容器触发状态切换
  • Modal组件自带关闭逻辑和编辑器风格样式,无需额外自定义

实现侧边栏(Plugin Sidebar)

如果需要打开编辑器原生侧边栏,先注册侧边栏,再通过数据调度触发打开动作:

import { dispatch } from '@wordpress/data';
import { PluginSidebar } from '@wordpress/edit-post';

// 先注册侧边栏
wp.plugins.registerPlugin('my-block-sidebar', {
  render: () => (
    <PluginSidebar name="my-block-sidebar" title="区块设置">
      <div style={{ padding: '16px' }}>
        <p>这里是侧边栏配置区域,可添加各类编辑器端控件</p>
      </div>
    </PluginSidebar>
  ),
});

const MyBlock = {
  title: '可打开侧边栏的区块',
  category: 'widgets',
  edit: () => {
    const openSidebar = () => {
      // 触发打开指定侧边栏的动作
      dispatch('core/edit-post').openGeneralSidebar('plugin/my-block-sidebar');
    };

    return (
      <div onClick={openSidebar} style={{ padding: '20px', border: '1px dashed #ccc', cursor: 'pointer' }}>
        <h3>点击打开侧边栏</h3>
      </div>
    );
  },
  save: () => {
    return <h1>This is the frontend.</h1>;
  }
};

wp.blocks.registerBlockType('my-plugin/sidebar-block', MyBlock);
  • 用wp.plugins.registerPlugin注册侧边栏,需指定唯一标识name
  • 通过dispatch('core/edit-post').openGeneralSidebar触发打开,参数为侧边栏完整标识(plugin/[name])

问题2:前端仅输出文本的wp.element用法

你的save函数可以直接返回字符串文本,或用createElement创建无标签文本节点,Gutenberg会在前端直接渲染纯文本:

方式1:直接返回字符串(最简洁)

save: function () {
  return 'This is the frontend plain text.';
}

前端输出:This is the frontend plain text.

方式2:用createElement创建文本节点

如果必须使用wp.element.createElement,可以省略标签名直接传入文本:

save: function () {
  return wp.element.createElement(null, null, 'This is the frontend plain text.');
}

说明:Gutenberg的save函数支持返回React元素、字符串或null,前端会直接渲染返回内容,无需额外包裹HTML标签。

内容的提问来源于stack exchange,提问作者Danykan Kandany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:50:08