I am working on React-Native, i want to call a function from different class but when i am trying to do it's showing some error.
Class A
import B from './B.js'; class A extends Component { _onItemPressed(item){ B.abc(); } render() { return ( <TouchableHighlight underlayColor={Colors.colors.lightgrey} style={{padding: 15}} onPress={this._onItemPressed.bind(this)}> <Text>Click Me !</Text> </TouchableHighlight> ); } }
Class B
class B extends Component { abc(){ alert('Hello World'); } render() { return ( <View> <Text>Welcome to React Native</Text> </View> ); } }
But error message is coming after pressing the button in Class A, 'undefined is not a function (evaluating 'B.default._abc()')'
Please kindly go through my post and suggest me some solution.
Thanks
To call a method from another class component in React. js, we can pass the class method as a prop to a child component. We have components Class1 and Class2 . And Class1 is a child of Class2 .
To call a function, you can either pass its name and arguments to User. callFunction() or call the function as if it was a method on the User. functions property.
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> ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With