0

我正在为 Math-Tuition(React-native 移动应用程序)开发一个项目,并wiris用于设置问题和答案。wiris 在 MathML 中发送这些问题,我正在使用 npm package 将 MathML(方程、图形等)转换为 JSX react-native-mathjax

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

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

import React, { Component } from 'react';

从'react-native'导入{文本,视图,样式表};从 'react-native-webview' 导入 { WebView };

导出默认类 sampleReactApp extends Component { render() { let 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>
    );
}

}

4

1 回答 1

0

如果你看官方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道具设置WebVieworiginWhitelist={['']}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}
            />
        )
    }
}
于 2020-11-02T08:56:34.817 回答