SukhiX07
SukhiX07

Reputation: 27

Calling Function from Another Class React-Native

I am trying to call a function from another class. All i need is when i press the button it should console log an output to my browser.I tried making some steps but it throws an error saying "Cannot read property of message". Here's my code

import React, { Component } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import messageClass from "./message"

class App extends Component{

 onPress = ()=>{
  this.setState({FromStr: this.state.From})
  this.setState({ToStr: this.state.To})
  messageClass.message()
 }

 render(){
  return (
   <View style={styles.buttonStyle}>
     <Button
       title={"Press"}
       color="#FFFFFF"
       onPress={this.onPress}
     />
   </View> 
  );
 }
}

message.js

import { Component } from "react";
export default class messageClass  extends Component{
    message(){
        console.log("Hiiiii")
    }
}

Upvotes: 0

Views: 375

Answers (1)

ihsnktmr
ihsnktmr

Reputation: 220

Maybe you can try to use static method ?

import React, { Component } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import messageClass from "./MessageClass"

export default class App extends Component{
     onPress = ()=>{
        messageClass.message()
     };

    render(){
        return (
            <View style={{width:100, height:50}}>
                <Button
                    title={"Press"}
                    color="#FFFFFF"
                    onPress={this.onPress}
                />
            </View>
        );
    }
}

import { Component } from "react";

export default class messageClass  extends Component{
    static message(){
        console.log("foo")
    }
}

Upvotes: 2

Related Questions