首页 > 解决方案 > Gutenberg 自定义块如何将数据从插件索引文件发送到 js 文件

问题描述

我已经在插件主/索引 php 文件中注册了自定义块。

register_block_type('gutenberg-custom/show-information', array(
        'editor_script' => 'gutenberg-show-information',
        'style' => 'gutenberg-customblock-css',
    ));

我想将此 PHP 文件中的一些数据发送到包含该块的实际实现的 js 文件。原因是,我需要从 PHP 进行 API 调用,并在 js 代码的选择框选项中使用该响应。请参阅下面的注释代码。这是js的代码。

edit: function(props) {
      console.log("props", props);
      return el(
        Fragment,
        {},
        el(
          InspectorControls,
          {},
          el(
            PanelBody,
            { title: "Show Settings", initialOpen: true },
            el(
              PanelRow,
              {},
              el(SelectControl, {
                label: "Select Exhibitor",
                options: [    // **these options are static I have given but I want these to be dynamic coming from the plugin main file or can be any PHP file 
                  { label: "Big", value: "100%" },
                  { label: "Medium", value: "50%" },
                  { label: "Small", value: "25%" }
                ],
                onChange: value => {
                  props.setAttributes({ exhibitor_id: value });
                },
                value: props.attributes.exhibitor_id
              })
            )
          )
        ),
        el(
          "div",
          {},
          "[show-information]"
        )
      );
    },

标签: wordpresswordpress-gutenberggutenberg-blockscreate-guten-block

解决方案


当您将编辑器脚本排入队列时,您可以“注入”传递给 JS 的变量:

wp_register_script('gutenberg-show-information', $pathToScript, [], null, true);
wp_localize_script(
  'gutenberg-show-information',
  YOURJSOBJECT,
  ['myVar' => 'foobarbaz'] <--- array of data you want to pass
);
wp_enqueue_script('gutenberg-show-information');

在您的 javaScript 文件中,您可以访问YOURJSOBJECT.myVar应该输出 foobarbaz


推荐阅读