React Native: How to add script tag in the component

穿精又带淫゛_ 提交于 2020-01-04 05:42:15

问题


I am trying to add tag inside the component for the React Native app. Below is my code and it doesn't seem to work. Could anyone please tell me how to solve this issue?

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>
    );
  }
}

回答1:


My guess is that the code you are writing will not run in a browser. The script tag serves to tell the BROWSER: "Hey browser, stop. We got some javascript here. Execute it", so you should forget about the script tag.




回答2:


You could do that logic in componentDidMount instead.

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:


You cannot execute code depending on browser environment on react-native. try to run it inside a WebView component. https://facebook.github.io/react-native/docs/webview.html



来源:https://stackoverflow.com/questions/51139829/react-native-how-to-add-script-tag-in-the-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!