This tutorial explains how to Call Functions of Other Class From Current Class in React Native application. If you read java, c++ and other object oriented programming languages, then you must be remembering about parent and child class relationship. In order to access function and variable of another class we need to create object instance of that particular class. In react and react native we can create similar functionalities in order to access other class function and variable.
Lets see the below example, where we have two classes App and AlertClass class. In order to access features of AlertClass class in App class we need to create object of AlertClass in App class with new keyword and then we can have access to all the functions.
App.js
Lets see the complete source code for app class.
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, Button } from 'react-native'; export default class App extends Component { callWithoutArgument = () => { //Calling a function of other class (without arguments) new AlertClass().defaultArgumentFunction(); }; callWithArgument = () => { //Calling a function of other class (with argument) new AlertClass().parameterisedFunction('Welcome to skptricks'); }; render() { return ( <View style={styles.container}> <View style={{ margin: 10 }}> <Button title="Function Without Argument" onPress={this.callWithoutArgument} color="#E91E63" /> </View> <View style={{ margin: 10 }}> <Button title="Function Without Argument" onPress={this.callWithArgument} color="#E91E63" /> </View> </View> ); } } class AlertClass extends Component { defaultArgumentFunction = () => { //function to be called from default class (without args) alert('Function is Called Without Argument '); }; parameterisedFunction = Value => { //function to called from default class (with args) alert(Value); }; } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, });
Screenshot :
This is all about Example to Call Functions of Other Class From Current Class in React Native. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
No comments:
Post a Comment