在我的index.html中,我有以下代码:
<head>
...
<script type="text/javascript"
src="https://mysrc.com/something.js&collectorId=f8n0soi9"
</script>
<script type="text/javascript">window.ATL_JQ_PAGE_PROPS = {
'f8n0soi9': {
"triggerFunction": function (showCollectorDialog) {
document.getElementById("button1").addEventListener("click", function (e) {
e.preventDefault();
showCollectorDialog();
});
}
}
};</script>
</head>然后在我的myComponent.tsx文件中,我在页面上的某个地方有一个按钮,如下所示:
function myComponent() {
return (
...
<button id="button1">
Button Text
</button>
...
);
}
export default myComponent;还需要注意的是,我正在使用react-routing在不同组件之间导航,上面的按钮只是其中一个组件
因此,问题似乎是,如果您加载到任何其他网页上的站点,然后导航到带有按钮的页面,则除非您刷新该特定页面,否则按钮将不起作用,因为它可能不在加载的第一个页面上,并且可能没有找到id为"button1“的元素来绑定事件侦听器。默认情况下,在站点中导航时,React-routing不会刷新页面。
将我在index.html文件中的代码放到myComponent.tsx文件中也不起作用,因为(我认为) index.html文件允许任何原始html,但是tsx文件不是真正的html?有没有办法在index.html文件中将其定义为函数,然后将onClick事件分配给按钮?提前感谢大家!
发布于 2021-06-23 23:08:13
是的,应该可以绑定显示对话框以供以后使用的函数,然后在按钮上使用推荐的React事件。在此示例中,为简单起见,全局绑定到window对象:
"triggerFunction": function (showCollectorDialog) {
window.showCollectorDialog = showCollectorDialog;
}
// ...
<button id="button1" onClick={e => {e.preventDefault(); window.showCollectorDialog();}}>如果遇到Type错误,请尝试(在按钮上):
=> {...; (window as any).showCollectorDialog();}或者仅声明属性(如果签名已知,则可能比此处的any更具体):
declare global {
interface Window { showCollectorDialog: any; }
}把它放在你的TS源中的某个地方应该没问题,你的index.html不需要TS就可以分配它。
https://stackoverflow.com/questions/68102338
复制相似问题