cjmling cjmling - 3 months ago 13
React JSX Question

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

Answer

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