javascript - 如何在 react-native 应用程序中使用用外部文件编写的 javascript 函数?
问题描述
我正在为 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>
);
}
}
解决方案
如果你看官方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}
/>
)
}
}
推荐阅读
- opencv - 减少快速移动球的运动模糊
- google-chrome - google cloud shell 暂时不可用,几分钟后再试
- javascript - 为什么我的反应应用程序中的 fetch 语句会导致两次调用?
- flutter - 如何在 Appbar Flutter 中反转 RoundBottom
- java - 为什么无法导入org.springframework.data 无法解决
- python - 如何修复有关缺少方法的 AttributeError?
- magento - 为什么 region_code 不能正确存储?
- c# - 如何使用 c# razor 语法从下拉列表的选定项目中访问数据属性
- elasticsearch - 如何在任何嵌套字段中搜索值?
- sql-server - 如何在 Azure Synapse 中实现序列