javascript - 如何将脚本函数添加到 React
问题描述
我正在尝试将外部应用程序 Chameleon 添加到我的反应应用程序中,为此我必须将javascript 函数添加到我的应用程序中。
我只希望在特定情况下调用它,所以我不想将它加载到我的index.html
. 我尝试将它添加到render
我的组件的功能中:
render() {
return(
<div>
<head>
<script type="text/javascript">/* Chameleon - better user onboarding */!function(t,n,o){var a="chmln",c="setup identify alias track clear set show on off custom help _data".split(" ");n[a]||(n[a]={}),n[a].accountToken=o,n[a].location=n.location.href.toString();for(var e=0;e<c.length;e++)!function(){var t=n[a][c[e]+"_a"]=[];n[a][c[e]]=function(){t.push(arguments)}}();var s=t.createElement("script");s.src="https://fast.trychameleon.com/messo/"+o+"/messo.min.js",s.async=!0,t.head.appendChild(s)}(document,window,"TOKEN");
chmln.identify(USER.ID_IN_DB, { // Unique ID of each user in your database (e.g. 23443 or "590b80e5f433ea81b96c9bf6")
email: USER.EMAIL });
</script>
...
...
</head>
</div>
)
}
但上面的方法似乎不起作用。我在头盔内尝试了同样的方法,但没有运气。他们都显示一个错误
SyntaxError: Unexpected token
有没有办法可以在特定组件中加载此功能,还是必须在index.html
?
解决方案
您似乎对 react 的用途和使用方式有很大的误解。
1) 页面上应该只有 1 个head
元素,并且它不应该出现在index.html
组件的渲染输出中。
2)让组件渲染<script>
标签违背了使用反应的观点。
您需要做的是import
组件中需要的代码:
import './path/to/file.js'
然后从那里chmln
应该可以在window
对象上使用
window.chmln.identify()
推荐阅读
- javascript - fullcalendar 谷歌隐藏过去的事件
- javascript - 如何在 React 中控制音频/视频 DOM 元素
- html - 日文电子邮件网络字体
- google-chrome - 有没有办法在浏览器中执行事件跟踪?
- c - C程序在数组json中使用对象时不起作用
- php - Apache 配置和会话变量 SERVER_NAME
- javascript - 一次消耗 3 个元素的 AsyncGenerator?
- php - Google Sheet API 的问题
- java - spring boot 2.1.6 with zipkin,使用spring boot应用调试项目抛出异常
- php - Laravel AJAX 500 内部错误,没有消息