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

Dri*_*oor 4 javascript wordpress wordpress-gutenberg gutenberg-blocks

使用 Wordpress 自定义块,我目前正在尝试创建一个包含按钮和隐藏内容的弹出框组件。当用户单击或将鼠标悬停在按钮上(在网站的前端,而不是块编辑器中)时,应显示隐藏内容。

但是,当我向按钮添加onClick或 时onHover,事件处理程序不会执行。

此外,尝试使用useState挂钩来存储弹出窗口的显示状态会导致我的块编辑器崩溃。

这就是我的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>
    )
}
Run Code Online (Sandbox Code Playgroud)

这个类似(?)问题的答案似乎表明这是不可能的,因为前端只是渲染“静态html”并剥离了javascript。如果是这种情况,在 WordPress 自定义块的前端创建用户交互性(悬停/单击事件甚至可能的 http 请求)的好方法是什么?

小智 7

从 WordPress 5.9.0 开始,您必须使用 viewScript 在 block.json 中定义前端 JS 文件:

{ "viewScript": "file:./view.js" }
Run Code Online (Sandbox Code Playgroud)

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