【问题标题】:React Native: How to add script tag in the componentReact Native:如何在组件中添加脚本标签
【发布时间】:2018-12-10 21:32:16
【问题描述】:

我正在尝试在 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>
    );
  }
}

【问题讨论】:

  • nmjs.com/package/react-load-script 现在已被废弃且无人维护。

标签: javascript reactjs react-native react-redux


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 感谢您的回答。但这行不通……我拥有的脚本是我想在应用程序上显示的聊天机器人。你的回答没有做到这一点。你知道如何实现吗?
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2017-03-18
      • 2016-10-31
      • 2019-05-17
      • 2018-07-28
      • 2022-01-21
      • 2023-04-08
      • 2019-07-05
      • 2019-11-20
      相关资源
      最近更新 更多