在本地应用程序中如何使用写在外部文件中的javascript函数?

问题描述

我正在为Math-Tuition(本机反应式移动应用程序)开发一个项目,并使用wiris设置问题和答案。 wiris在MathML中发送了这些问题,我正在使用npm软件包react-native-mathjax将MathML(等式,图形等)转换为JSX。

我的Web团队已经在vue.js中在Web上进行了开发,wiris还提供了输入felids变量以编写答案,我需要使用一些javascript函数对这些变量进行一些中间计算/重新格式化,这些函数已编写在使用javascript的外部文件和使用相同文件的Web开发人员(vue.js)中。

我试图在Webview中注入js代码,但是无法在react-native中导入该js函数文件,有人可以建议我更好吗。提前致谢 :) 我正在共享导入js文件代码。如果我编写外部js文件的路径错误代码甚至不会出错。

import React,{ Component } from 'react';

从'react-native'导入{Text,View,StyleSheet}; 从'react-native-webview'导入{WebView};

导出认类sampleReactApp扩展了组件{ render(){ 让HTML = <html> <head> <script type="text/javascript" src="./quizzes.js"></script> </head> <body> <div id="workbookControl"></div> <div id="tableeditor" style="font-size : 50px;">I am written inside source HTML</div> <div id="msg" onclick="javascript:alert('Hi')" style="font-size : 50px;" >notify alert</div> </body> </html>; 让jsCode = alert("Js");;

    return (
        <View style={{flex: 1}}>
            <WebView ref={ref => { this.webview = ref; }}
                source={{ html: HTML }}
                injectedJavaScript={jsCode}
                javaScriptEnabledAndroid={true}
                javaScriptEnabled={true}
            >
            </WebView>
        </View>
    );
}

}

解决方法

如果您查看官方WebView文档,则HTML必须是用引号引起来的字符串。另外,在下面,要使注入的javascript代码正常工作,您需要传递onMessage道具(请参见此处:https://github.com/react-native-webview/react-native-webview/issues/1260)。因此,只需传递一个空函数即可解决该问题。同样根据官方文档(https://github.com/react-native-webview/react-native-webview/issues/1260),它要求您在末尾包含true;,以防止出现静默故障。最后,加载静态html要求您将originWhitelist中的WebView属性设置为originWhitelist={['']}https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md#source

import React from 'react'
import { WebView } from 'react-native-webview'

export default class sampleReactApp extends React.Component {
    render () {
        var HTML = `<html> <head> <script type="text/javascript" src="./quizzes.js"></script> </head> <body> <div id="workbookControl"></div> <div id="tableeditor" style="font-size : 50px;">I am written inside source HTML</div> <div id="msg" onclick="javascript:alert('Hi')" style="font-size : 50px;" >notify alert</div> </body> </html>`
        var jsCode = `alert('hello world'); true;`
        return (
            <WebView
                originWhitelist={['*']}
                source={{ html: HTML }}
                injectedJavaScript={jsCode}
                onMessage={() => {}}
                javaScriptEnabledAndroid={true}
                javaScriptEnabled={true}
            />
        )
    }
}