如何在本机中创建全局辅助函数?

Phy*_*hyo 11 react-native

如何创建Global Helper功能react-native

我想用于访问sqlite数据库或从服务器获取数据.我可以创建一个JavaScript包含函数的文件并从多个视图调用该函数吗?

Nad*_*bit 18

我们过去做过的方式:

  1. 创建导出函数的文件:

    module.exports = function(variable) {    
       console.log(variable);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在变量中要求使用文件时需要该文件:

    var func = require('./pathtofile');
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用功能:

    func('myvariable');
    
    Run Code Online (Sandbox Code Playgroud)

  • 你能否告诉我们如何进行回调以返回一些结果? (3认同)

Mah*_*our 5

全局变量

class MainActivity extends Component {

  constructor(){
     super();

     // Creating Global Variable.
     global.SampleVar = 'This is Global Variable.';
  }
}
Run Code Online (Sandbox Code Playgroud)

在第二个活动中

class SecondActivity extends Component {

  render(){
    return(
       <View>
          <Text> {global.SampleVar} </Text>
       </View>
   );
  }
}
Run Code Online (Sandbox Code Playgroud)

但如果你想有一个全局功能

export function TestFunc1() {

}

export function TestFunc2() {

}
Run Code Online (Sandbox Code Playgroud)

然后导入并使用

import { TestFunc1 } from './path_to_file'
Run Code Online (Sandbox Code Playgroud)