0

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")
    }
}
1

1 Answer 1

2

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")
    }
}

Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure that you imported messageClass.js to App.js properly ?
How can i call it without "static" because state wont let me to change the state of my program
If you want to change state from another parent class you should use redux to manage your data and control your states with shoudlComponentUpdate() function I'd recommend you to check these out; redux.js.org and reactjs.org/docs/react-component.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.