首页 > 解决方案 > 如何将脚本函数添加到 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?

标签: javascriptreactjsasynchronousreact-helmet

解决方案


您似乎对 react 的用途和使用方式有很大的误解。

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

2)让组件渲染<script>标签违背了使用反应的观点。

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

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

然后从那里chmln应该可以在window对象上使用

window.chmln.identify()

推荐阅读