简体   繁体   English

如何从另一个类 React-native 调用函数

[英]How to call a function from another class React-native

I am trying to call a function from another class it throws an error getValue is not a function.我试图从另一个类调用一个函数,它抛出一个错误 getValue is not a function。 i dont want to use static.我不想使用静态。 I hope there's a solution for it.我希望有一个解决方案。 here's my code这是我的代码

import React, { Component } from "react";
import SecondClass from "./main"

export default class A extends Component{
  constructor (props) {  
    super(props)

 onPress = ()=>{
   getValue()

 }
}

//SecondClass
export default class SecondClass extends Component{
  constructor (props) {  
    super(props)
  }
  getValues = () => {
    alert("Hello")
  }   
}

我认为您需要在A定义函数,然后将SecondClass组件中的函数作为道具传递...

https://www.npmjs.com/package/react-native-simple-events

You can use this library here you can register your function and can trigger from anywhere in app.你可以在这里使用这个库,你可以注册你的函数,并且可以从应用程序的任何地方触发。

For register your function use on("eventID", "listenerID", ()=>{//call getValues}) in class SecondClass要注册您的函数on("eventID", "listenerID", ()=>{//call getValues})在类SecondClass使用on("eventID", "listenerID", ()=>{//call getValues})

For Trigger your function use trigger("eventID", eventData) in class A对于触发器你的函数在类A使用trigger("eventID", eventData)

After that remove the listener by using remove("eventID", "listenerID") from class SecondClass之后使用remove("eventID", "listenerID")从类SecondClass remove("eventID", "listenerID") SecondClass

You cannot expect that you can simply call some function in another class because you imported that class.你不能指望你可以简单地调用另一个类中的某个函数,因为你导入了那个类。 The React way of doing this would be to pass the function as a prop if these are parent-child components.如果这些是父子组件,React 这样做的方法是将函数作为 prop 传递。 If not, I would highly recommend extracting the common function out from both classes and call them separately.如果没有,我强烈建议从两个类中提取通用函数并分别调用它们。

From the comments, other users have also recommended using static function if you absolutely want to couple the function to Second class.从评论中,如果您绝对想将函数耦合到Second class,其他用户也建议使用static函数。

My main objective is when user press the button then it should call the method from another class and return Hello.我的主要目标是当用户按下按钮时,它应该从另一个类调用该方法并返回 Hello。 Then later i want to set some properties which i not possible in static function.然后我想设置一些在静态函数中无法实现的属性。 So thats why i dont want to use static function所以这就是为什么我不想使用静态函数

From your sample code it looks like Second is a React component ?从您的示例代码看起来Second是一个 React 组件? If this class was made to encapsulate certain behavior then I would recommend turning it into a plain javascript class and then instantiate/use wherever necessary.如果这个类是为了封装某些行为,那么我建议将它变成一个普通的 javascript 类,然后在必要时实例化/使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM