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

IT技术 javascript reactjs react-native react-redux
2021-05-04 13:43:55

我正在尝试在 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个回答

我的猜测是您编写的代码不会在浏览器中运行。脚本标签用于告诉浏览器:“嘿浏览器,停止。我们这里有一些 javascript。执行它”,所以你应该忘记脚本标签。

您可以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>
    );
  }
}

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