问题描述
我试图在react native中从外部文件调用普通的javascript函数,但是它没有运行。请提出一种注入普通javascript函数的方法。
我尝试使用WebView:
<View style={{flex: 1}}>
<WebView ref={ref => { this.webview = ref; }}
source={{ html: HTML }}
injectedJavaScript={jsCode}
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
>
</WebView>
</View>
解决方法
创建一个外部.js文件,在其中编写代码。
module.exports.yourFuncName = (params) => {
// your function def
}
OR
module.exports.yourFuncName = function (params){
// your function def
}
只需在组件中导入。
import { yourFuncName } from "location of file in code";
let jsCode = `
yourFuncName(params)
`;
<View style={{flex: 1}}>
<WebView ref={ref => { this.webview = ref; }}
source={{ html: HTML }}
injectedJavaScript={jsCode}
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
>
</WebView>
,
module.exports.Example = (params) => { alert("123456") }
然后
import {Example} from 'fileName.js'
如果其index.js文件仅指定文件夹的路径