从另一个类React-Native调用函数

时间:2020-01-28 15:26:21

标签: reactjs react-native

我试图从另一个类调用一个函数。我所需要的是,当我按下按钮时,它应该控制台将输出记录到我的浏览器中。我尝试执行一些步骤,但是它抛出一个错误,提示“无法读取消息的属性”。这是我的代码

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 个答案:

答案 0 :(得分:1)

也许您可以尝试使用静态方法?

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