简体   繁体   中英

How to access props in other functions of imported modules

Let say i created a basic modules with simple functions like helper.js

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

export function HelloTester() {
  HelloChandu();
}

Then I imported this module in my component as import * as Helper from './helper';

In some element I then called onpress={Helper.HelloTester.bind(this)} So by this now I can access this.props in HelloTester function but I can not access this.props in HelloChandu function.

Question : How can I access this.props from any function in my helper.js module ? Like if there are 10-20 functions , and i don't have to pass as parameters around.

Thank You

I am afraid that if you want to access this.props in one of your functions you will need to pass this explicitily or to bind all the functions to the current this before using them.

There are several ways to do so.

 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)() 

An alternative way would be to wrap all the functions in another function.

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

1.You can persist props to AsyncStorage, whenever you need, you can access this props.

2.Or if you are familiar with closure, you can do like this :

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();

then you should export Helper, and import Helper from 'Helper.js'

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

export function HelloTester(_this) {
  HelloChandu(_this);
}

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