[英]How to use javascript functions written in external file, in react-native application?
我正在为 Math-Tuition(React 原生移动应用程序)开发一个项目,并使用wiris
设置问题和答案。 wiris 在 MathML 中发送这些问题,我正在使用 npm 包react-native-mathjax
将 MathML(方程、图形等)转换为 JSX。
我的 web 团队在 vue.js 中在 web 上开发了相同的,wiris 还提供输入 felids 变量来编写答案,我需要使用一些 javascript 函数对这些变量进行一些中间计算/重新格式化,这些函数是用外部编写的javascript 中的文件和相同的文件 web developer(vue.js) 使用。
我试图在 webview 中注入 js 代码,但无法在 react-native 中导入该 js 函数文件,有人可以更好地建议我吗。 在此先感谢:) 我正在共享导入 js 文件的代码。 如果我写了错误的外部 js 文件路径,代码甚至不会出错。
import React, { Component } from 'react';
import { Text, View, StyleSheet } from '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>
<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/参考.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}
/>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.