如何在脚本标签中初始化var?

时间:2019-04-09 21:37:59

标签: javascript reactjs

这是我正在建立的第一个网站,我想使用的api要求我在像这样的脚本内创建一个变量。

<script>
var someVariable = {
  api_key: "api_key_here",
  debug: true
};
</script>

当我将其放入index.html中时,文件将编译并且api成功。但是,如果我尝试将相同的代码片段放入React的render方法中,则会得到:

  

“}预期”在“ api_key”之后

我尝试dangerouslySetInnerHTML运行代码和其他一些技巧,但是即使它们可以编译,在运行时我也会收到这样的错误。

  

对象作为React子对象无效(找到:带有键的对象   {api_key,debug})。如果您打算渲染儿童集合...

我在此问题上停留了最长的时间,无法在互联网上找到解决方案。如果有人能帮助我指出正确的方向,我将不胜感激。谢谢。

完整渲染方法

render() {
    return (
      <div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
  var pollfishConfig = {
    api_key: "api_key_goes_here",
    debug: true
  };
</script>
<script src="https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js"></script>
      </div>
    )}

编辑: 我能够使用componentDidMount()使它正常工作

  componentDidMount() {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.innerHTML = "var pollfishConfig = {api_key: \"api_key_here\", debug: true,
closeCallback: customSurveyClosed}; function customSurveyClosed(){console.log("test");}";
    document.body.appendChild(s);
  }

有没有办法使函数customSurveyClosed访问其中调用componentDidMount的react类?例如,在customSurveyClosed()内部,更改react组件的状态。

2 个答案:

答案 0 :(得分:0)

我不会将script标签放置在您的render方法中。而是在用于执行API调用的函数中创建变量。这是一个示例:

export default class Form extends Component {

  signup = e => {
    var someVariable = {
      api_key: "api_key_here",
      debug: true
    };
    // other code logic
  }

  render() => {
    <button onClick={this.signup}>Click me!</button>
  }
}

答案 1 :(得分:0)

您可以在应用程序类中使用 componentWillMount 。并通过它添加全局变量。像这样:

componentWillMount: function () {
    window.someVariable = {
        api_key: "api_key_here",
        debug: true
    };
}