如何访问导入模块的其他功能中的道具

How to access props in other functions of imported modules

本文关键字:其他 功能 模块 导入 何访问 访问      更新时间:2023-09-26

假设我创建了一个具有简单功能的基本模块,如helper.js

export function HelloChandu() { 
   //How to access navigator props from here.
}
export function HelloTester() {
  HelloChandu();
}

然后我在我的组件中导入了这个模块作为import * as Helper from './helper';

在某个元素中,我当时调用了onpress={Helper.HelloTester.bind(this)},所以现在我可以访问HelloTester函数中的this.ops,但不能访问HelloChandu函数中的this.props。

问题:如何从helper.js模块中的任何函数访问this.props?比如有10-20个函数,我不必作为参数传递。

谢谢

如果您想在其中一个函数中访问this.ops,则需要显式传递this,或者在使用它们之前将所有函数绑定到当前this

有几种方法可以做到这一点。

function HelloChandu() { 
  alert(this.props);
}
function HelloTester() {  
  HelloChandu.apply(this);
  // HelloChandu.call(this);
  // HelloChandu.bind(this)();
  // this::HelloChandu(); // Experimental!
}
const obj = {
  props: 'my props'
}
HelloTester.bind(obj)()

另一种方法是将所有函数封装在另一个函数中。

function helpers() { 
  const functions = {
    HelloChandu: () => {     
      alert(this.props);
    },
    HelloTester: () => {  
      functions.HelloChandu();    
    }
  };
  return functions;
}
const obj = {
  props: 'my props'
}
helpers.call(obj).HelloTester();

1.您可以将道具持久化到AsyncStorage,无论何时需要,您都可以访问此道具。

2.或者,如果你熟悉闭包,你可以这样做:

function Helper(ps) {
  function test() {
    console.log(ps.sex);
  }
  function test2() {
    console.log(ps.name);
  }
  return {
    test: test,
    test2: test2,
  }
}
var obj = Helper({name: 'abc', sex: 'male'});
obj.test(); 
obj.test2();

然后应该导出Helper和import Helper from 'Helper.js'

export function HelloChandu(_this) { 
   //How to access navigator props from here.
}
export function HelloTester(_this) {
  HelloChandu(_this);
}