如何向React添加脚本功能

时间:2019-04-02 20:45:39

标签: javascript reactjs asynchronous react-helmet

我正在尝试将外部应用程序Chameleon添加到我的react应用程序中,为此,我必须将javascript function添加到我的应用程序中。

我只希望在特定情况下调用它,所以我不想将其加载到我的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中执行此操作?

1 个答案:

答案 0 :(得分:2)

您似乎对React的用途以及用法有误解。

1)页面上只能有1个head元素,并且应该在index.html中,而不是组件的呈现输出中。

2)让组件呈现<script>标签与使用react的观点背道而驰。

您需要做的是import您需要在组件中添加的代码:

import './path/to/file.js'

然后chmln对象上应该有window

window.chmln.identify()
相关问题