[英]How do I add JavaScript to a Wordpress Gutenberg custom block?
使用 Wordpress 自定義塊,我目前正在嘗試創建一個包含按鈕和隱藏內容的彈出組件。 當用戶單擊或懸停在按鈕上時(在網站的前端,而不是在塊編輯器中),應該會出現隱藏的內容。
但是,當我向按鈕添加onClick
或onHover
時,不會執行事件處理程序。
此外,嘗試使用useState
掛鈎存儲彈出框的顯示 state 會使我的塊編輯器崩潰。
這是我的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>
)
}
這個類似(?)問題的答案似乎表明這是不可能的,因為前端只是呈現“靜態 html”並剝離 javascript。 如果是這種情況,在 Wordpress 自定義塊的前端創建用戶交互(懸停/單擊事件甚至可能的 http 請求)的好方法是什么?
在您的 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"
}
參考https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script
現在,我已經能夠通過在我為自定義塊創建的 Wordpress 插件中加入自定義腳本來解決問題:
但是,如果有人找到更好的解決方案,我會很想知道!
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 (入隊腳本)
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 (自定義塊的保存功能)
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>
)
}
從 WordPress 5.9.0 開始,您必須使用 viewScript 在 block.json 中定義前端 JS 文件:
{ "viewScript": "file:./view.js" }
請參閱參考: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.