简体   繁体   中英

React-native: Export function using 'this' from other component

I'm actually having an issue in my React-native logic and I need your precious help !

I have my main component 'Main.js' and I want to import a function from 'Function.js' that should change the state of 'Main.js'...

But of course I don't have access to "Main.js"'s this . So my question is:

How can I change the Main.js state from an exported function in Function.js ?

Here is the kind of code in Function.js

_function = () => {
   ... Getting MyState in AsyncStorage ...
   var MyState = ...;
   this.setState({ User: MyState })
}

And my Main.js

import { _function } from 'Function.js'
...
componentDidMount(){
   this._function()
}
...

Either make the instance a parameter of the function:

export const _function = (main) => {
   // ... Getting MyState in AsyncStorage ...
   var MyState = …
   main.setState({ User: MyState })
};

import { _function } from 'Function.js'
…
  componentDidMount(){
    _function(this)
  }
…

Or don't use an arrow function so that you can actually use it as a method:

export function _function() {
   // ... Getting MyState in AsyncStorage ...
   var MyState = …
   this.setState({ User: MyState })
};

import { _function } from 'Function.js'
…
  componentDidMount(){
    _function.call(this)
  }
…

You could even install it as a real method:

import { _function } from 'Function.js'
class Main {
  componentDidMount(){
    this.method();
  }
}
Main.prototype.method = _function;

You can pass a function in your _function parameters.

In main.js, you would have a function

setUser = (User) => {
  this.setState({user});
}

Then you call _function and pass setUser as a parameter.

componentDidMount(){
  _function(this.setUser)
}

In Function.js, you edit your function to receive the function and call it.

_function = (setUser) => {
 ... Getting MyState in AsyncStorage ...
 var MyState = ...;
 setUser(MyState);
}

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