Reputation: 18863
How to run method between two separate class in React Native.
for example:
first class
export default class Test1 extends Component {
testMethod(){
// ...
}
render() {
...
}
}
and in second class
export default class Test2 extends Component {
componentWillMount(){
Test1.testMethod();
}
render() {
...
}
}
Upvotes: 0
Views: 64
Reputation: 18863
Here is a simple way of doing it...
export default class CommonDataManager {
static myInstance = null;
_userID = "";
/**
* @returns {CommonDataManager}
*/
static getInstance() {
if (CommonDataManager.myInstance == null) {
CommonDataManager.myInstance = new CommonDataManager();
}
return this.myInstance;
}
getUserID() {
return this._userID;
}
setUserID(id) {
this._userID = id;
}
}
And here is how to use it...
import CommonDataManager from './CommonDataManager';
// When storing data.
let commonData = CommonDataManager.getInstance();
commonData.setUserID("User1");
// When retrieving stored data.
let commonData = CommonDataManager.getInstance();
let userId = commonData.getUserID();
console.log(userId);
Hope this works out for you :)
Upvotes: 0
Reputation: 180
Your testMethod should be outside the class like following
export const testMethod = () => {
// ...
}
export default class Test1 extends Component {
render() {
...
}
}
If you wanted to modify object properties of class Test1, you can pass them as parameters of testMethod() and changes will be repercuted
Upvotes: 2