【问题标题】:How to create global helper function in react native?如何在本机反应中创建全局辅助函数?
【发布时间】:2016-02-06 00:07:35
【问题描述】:

如何在react-native 中创建全局帮助函数?

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

【问题讨论】:

标签: react-native


【解决方案1】:

我是这样简单的:

  1. 我创建了一个 helpers.js 文件,该文件将包含我项目的所有辅助函数并将其放置如下:./src/helpers.js(你可以放置在任何你喜欢的地方)。

  2. helpers.js导出这样的函数:

    export function GlobalLogout(str) {.....}

  3. 然后我像这样导入函数:

    import { GlobalLogout } from '../src/helpers';

  4. 最后像这样使用文件中的函数:

    GlobalLogout(data);

希望这对任何人都有帮助!

【讨论】:

    【解决方案2】:

    2种方法,不知道哪一种更好:

    1. 方法

    用途:

    window.foo = function(val) {
       alert(val);
    }
    
    1. (不是真正的全局)在您的class 中,您可以在need-to-use 文件中导出和要求,您可以定义您的函数。

    看这个:

    var React = require('react-native');
    
    var {
      View,
    } = React;
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      }
    });
    
    var MoviesScreen = React.createClass({
      foo : function(val) {
        alert(val);
      },
    
    render: function() {
        return (
          <View style={styles.container}>      
          </View>
        );
      },
    });
    
    
    module.exports = MoviesScreen;
    

    【讨论】:

      【解决方案3】:

      我有这个辅助函数:

      function myfunction(foo)
      

      我将其全局声明为:

      global.myfunction = function myfunction(foo) {...};
      

      【讨论】:

        【解决方案4】:

        全局变量

        class MainActivity extends Component {
        
          constructor(){
             super();
        
             // Creating Global Variable.
             global.SampleVar = 'This is Global Variable.';
          }
        }
        

        在第二个活动中

        class SecondActivity extends Component {
        
          render(){
            return(
               <View>
                  <Text> {global.SampleVar} </Text>
               </View>
           );
          }
        }
        

        但是如果你想拥有一个全局函数

        export function TestFunc1() {
        
         }
        
        export function TestFunc2() {
        
        }
        

        然后导入使用

        import { TestFunc1 } from './path_to_file'
        

        【讨论】:

          【解决方案5】:

          我们过去的做法:

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

            module.exports = function(variable) {    
               console.log(variable);
            }
            
          2. 当你想使用该文件时需要它,在一个变量中:

            var func = require('./pathtofile');
            
          3. 使用功能:

            func('myvariable');
            

          【讨论】:

          • 能否请您展示如何进行回调以返回一些结果?
          猜你喜欢
          • 1970-01-01
          • 2015-12-01
          • 1970-01-01
          • 2011-02-18
          • 2016-03-14
          • 2020-05-14
          • 1970-01-01
          • 2015-04-02
          • 2022-01-08
          相关资源
          最近更新 更多