简体   繁体   中英

how to write plain javascript external function in react native?

I was trying to call a plain javascript function from an external file in react native but it is not running. Please suggest a way to inject a plain javascript function.

I have tried to use WebView:

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

Create an external .js file write your code there.

module.exports.yourFuncName = (params) => {
     // your function def
} 

OR

module.exports.yourFuncName = function (params){
     // your function def
} 

In your Component simply import.

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") }

and then

import {Example} from 'fileName.js'

If its index.js file just specify the path of the folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM