How to call a function from another class in React-Native?
You have two options, either to use an object or use class name, let's start with object
class B {
abc() {
alert("Hello World");
}
}
const b = new B();
export default b;
So when you call this file you can access the function abc like the following
import b from './B.js';
class A extends Component {
_onItemPressed(item){
b.abc();
}
...
The other way is to use class instead as follow
class B{}
B.abc = function(){
alert("Hello World");
}
module.exports = {
functions: B
};
So when you call this file you can access the function abc like the following
import b from './B.js';
class A extends Component {
_onItemPressed(item){
b.functions.abc();
}
...
Note: B class should not be a component, you can use it as a helper class.
also, you can enhance the way you deal with the object using singleton pattern as I already mention in React native- Best way to create singleton pattern
UPDATE: If you insist to use component instead of a class function, you can call it through reference, as follows:
export default class B extends Component {
constructor(props) {
super(props);
this.abc = this.abc.bind(this);
}
abc(){
alert('Hello World');
}
render() {
return null
}
}
now in A component you can call B by reference
import B from "./B.js";
class A extends Component {
_onItemPressed(item) {
this._b.abc();
}
render() {
return (
<TouchableHighlight
underlayColor={Colors.colors.lightgrey}
style={{ padding: 15 }}
onPress={this._onItemPressed.bind(this)}
>
<Text>Click Me !</Text>
<B ref={ref => (this._b = ref)} />
</TouchableHighlight>
);
}
}
You dont initiate your class, to solve this you need to change the B.abc()
to new B().abc()
;