如何将DOMContentloaded事件侦听器添加到nextJS中的文档?



我试图添加一个html代码片段到我的nextjs项目。该代码片段包含一个具有createButton函数的外部脚本。

<div id="examplebtn"></div>
<script type="text/javascript">
//<![CDATA[
document.addEventListener('DOMContentLoaded', function () {
createButton('Name', 'Phone');
});
//]]>
</script>
<script src="https://example.com.na/js/example.js"></script>

createButton函数呈现一个由id标识的按钮(在本例中是examplebtn),在原生html文档中它工作得很好。但是,在nextjs中,我无法向脚本中所示的DOMContentLoaded事件添加事件侦听器,因为它一旦加载DOM就会运行该函数。我试过使用Next/Script, useEffect钩子,原生html标签都无济于事。在文档完全加载之前,我如何将DOMContentLoaded事件侦听器添加到jsx组件,以便该函数可以在适当的时间运行?事先感谢您的帮助。

{编辑}为了更清晰,我添加了createButton的最终代码。由于合同的义务,我不能发布代码,所以它被编辑过,但它应该是有帮助的。

window
.ButtonComponent({
params,
onPay: function (v, vn, a, r, e) {
c = customFunct(moreParams);
PopupComponent({
params,
onCancel: function () {
console.log('called onCancel');
// stuff here
},
onSubmit: function (r) {
// stuff here
},
}).render('body');
},
})
.render('#examplebtn');
<div id="examplebtn"></div>
{    
document.addEventListener('DOMContentLoaded', function () {
createButton('Name', 'Phone');
});  
}

只要用block写你想写的任何脚本

最新更新