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

7

我正在尝试在React Native应用程序的组件中添加<Text>标签。以下是我的代码,但它似乎不起作用。请问有谁能告诉我如何解决这个问题?

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


<script> tags don't work in React Native. Even if this is on a web browser, be careful that the script will be executed on every re-render. I use this library to include <script> in my ReactJS web apps. https://www.npmjs.com/package/react-load-script - christopher_pk
nmjs.com/package/react-load-script现已被放弃和不再维护。 - Spencer Shattuck
我一直在寻找这个问题的答案。我听说可以使用React Native中的Webview注入第三方脚本标签并加载脚本标签功能。如果您有相关经验,请给出一个示例回答吗?我想要包含 timeonsite.js 脚本标签并测试它。 - webblover
3个回答

2

我的猜测是,您正在编写的代码不会在浏览器中运行。 script标签的作用是告诉浏览器:“嘿,浏览器,停下来。我们有一些javascript代码。执行它”,所以您应该忘掉script标签。


1

谢谢Filipe,我会去看看的。 - webblover

0
你可以将这个逻辑放在 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>
    );
  }
}

谢谢你的回答。但是这个方法行不通...我现在有的脚本是我想要在应用程序上显示的聊天机器人。你的回答并没有解决这个问题。你知道如何实现吗? - Eunicorn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接