简体   繁体   English

如何将 JavaScript 添加到 Wordpress Gutenberg 自定义块?

[英]How do I add JavaScript to a Wordpress Gutenberg custom block?

Using Wordpress custom blocks, I'm currently trying to create a popover component that contains a button and a hidden content.使用 Wordpress 自定义块,我目前正在尝试创建一个包含按钮和隐藏内容的弹出组件。 The hidden content should appear when the user clicks on or hovers over the button (on the frontend of the website, not in the block editor ).当用户单击或悬停在按钮上时(在网站的前端而不是块编辑器中),应该会出现隐藏的内容。

However, when I add an onClick or onHover to the button, the event handler is not executed.但是,当我向按钮添加onClickonHover时,不会执行事件处理程序。

Additionally, trying to use the useState hook to store the display state of the popover crashes my block editor.此外,尝试使用useState挂钩存储弹出框的显示 state 会使我的块编辑器崩溃。

This is what my save method code currently looks like:这是我的save方法代码当前的样子:

export default function save() {

    const [shouldDisplay, setShouldDisplay] = useState(false);

    const handleClick = () => {
        console.log('Click confirmed.');
        setShouldDisplay(!shouldDisplay);
    }

    return (
        <div {...useBlockProps.save()}>
            {/* Button with onClick handler */}
            <button onClick={() => handleClick()}>Show hidden content!</button>

            {/* Hidden content */}
            { shouldDisplay && <div class="popover-content">...</div> }
        </div>
    )
}

The answer to this similar(?) question seems to suggest it is not possible as the frontend just renders "static html" and strips off the javascript. 这个类似(?)问题的答案似乎表明这是不可能的,因为前端只是呈现“静态 html”并剥离 javascript。 If that is the case, what would be good approach to create user interactivity (hover/click events or even possible http requests) in the frontend of Wordpress custom blocks?如果是这种情况,在 Wordpress 自定义块的前端创建用户交互(悬停/单击事件甚至可能的 http 请求)的好方法是什么?

In your blocks.json file you can define a js file to be executed on the front end.在您的 blocks.json 文件中,您可以定义要在前端执行的 js 文件。

{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 2,
  "name": "create-block/xxxxx",
  "version": "x.x.x",
  "title": "xxxx",
  "category": "xxxx",
  "description": "xxxx",
  "attributes": {
    "example":{
      "type":"string"
    },
  "supports": {
    "html:": true
  },
  "textdomain": "xxxxx",
  "editorScript": "file:./xxxx.js",
  "editorStyle": "file:./xxxx.css",
  "script": "file:./index.js", <--
  "style": "file:./xxxx-xxxx.css"
}

Reference https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script参考https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script

For now I have been able to solve the issue by enqueueing a custom script in the Wordpress plugin I have created for my custom blocks:现在,我已经能够通过在我为自定义块创建的 Wordpress 插件中加入自定义脚本来解决问题:

But if anyone finds a better solution I would be very interested to know!但是,如果有人找到更好的解决方案,我会很想知道!

index.php : (the main plugin file) index.php : (主插件文件)

function my_blocks_popover_enqueue_script()
{   
    wp_enqueue_script( 'my_blocks_popover_script', plugin_dir_url( __FILE__ ) . 'popover/scripts/index.js' );
}
add_action('wp_enqueue_scripts', 'my_blocks_popover_enqueue_script');

index.js (the enqueued script) index.js (入队脚本)

document.addEventListener("DOMContentLoaded", function () {
    document
        .querySelectorAll(".my-blocks-popover__trigger")
        .forEach(function (el) {
            const dropdown = el.querySelector(".my-blocks-popover__dropdown");

            el.addEventListener("mouseover", (_e) => {
                dropdown.classList.add("my-blocks-popover__dropdown--show");
            });

            el.addEventListener("mouseout", (_e) => {
                dropdown.classList.remove("my-blocks-popover__dropdown--show");
            });
        });
});

save.js (the custom block's save function) save.js (自定义块的保存功能)

export default function save() {

    return (
        <div class="my-blocks-popover__trigger" {...useBlockProps.save()}>
            <button class="my-blocks-popover__button">Show hidden content!</button>
            <div class="my-blocks-popover__dropdown">...</div>
        </div>
    )
}

Since WordPress 5.9.0 you have to use viewScript to define the frontend JS file in the block.json:从 WordPress 5.9.0 开始,您必须使用 viewScript 在 block.json 中定义前端 JS 文件:

{ "viewScript": "file:./view.js" }

See the reference: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script请参阅参考: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM