React Native:如何在组件中添加脚本标签

时间:2018-07-02 15:53:52

标签: javascript reactjs react-native react-redux

我正在尝试在React Native应用程序的组件内部添加标签。下面是我的代码,它似乎不起作用。 谁能告诉我如何解决这个问题?

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Dimensions from 'Dimensions';
import {StyleSheet, View, TextInput, Image, Text} from 'react-native';

export default class Chatbot extends Component {
  render() {
    return (
      <View>
        <Text>Testing</Text>
        
		<script type="text/javascript">
		    window.__be = window.__be || {};
		    window.__be.id = "5b3a47b4b30a36000769d821";
		    (function() {
		        var be = document.createElement('script'); be.type = 'text/javascript'; be.async = true;
		        be.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.botengine.ai/widget/plugin.js';
		        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(be, s);
		    })();
		</script>

      </View>
    );
  }
}

3 个答案:

答案 0 :(得分:1)

您可以改为在componentDidMount中执行该逻辑。

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Dimensions from 'Dimensions';
import {StyleSheet, View, TextInput, Image, Text} from 'react-native';

export default class Chatbot extends Component {
  componentDidMount() {
    window.__be = window.__be || {};
    window.__be.id = "5b3a47b4b30a36000769d821";
    (function() {
      var be = document.createElement('script'); be.type = 'text/javascript'; be.async = true;
      be.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.botengine.ai/widget/plugin.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(be, s);
    })();
  }
  render() {
    return (
      <View>
        <Text>Testing</Text>
      </View>
    );
  }
}

答案 1 :(得分:1)

我的猜测是您正在编写的代码无法在浏览器中运行。 脚本标签用于告知浏览器:“嘿,浏览器,停止。我们在这里有一些JavaScript。执行它”,因此您应该忘记脚本标签。

答案 2 :(得分:0)

您不能根据react-native上的浏览器环境执行代码。尝试在WebView组件中运行它。 https://facebook.github.io/react-native/docs/webview.html