如何从 React.js 中的另一个类组件调用方法 [英] How do I call a method from another class component in React.js

查看:15
本文介绍了如何从 React.js 中的另一个类组件调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我必须对组件进行分类:
Class1:有一个点击按钮
Class2:有一个方法调用我的 api

基本上,我想要的是调用一个方法,该方法可以从另一个类中设置和编辑一个类中的状态.但我总是失败.

So I have to class components:
Class1: has a clickbutton
Class2: has a method calling my api

Basically, what I want is to call a method that sets and edits states inside one class from another class. But I keep failing.

Class1.js
export class Class1 extends Component {
   render() {
      return (
         <div onClick={must call Class2Method}></div>
      )
   }
}

Class2.js
export class Class2 extends Component {
   Class2Method(){
      Here I call my API, I set & call states, ...
   }
   render {
      return (
         <Class1 />
         Here I return my API content
      )    
   }   
}

我尝试了什么:

  1. 我尝试使用我的方法并在我的 App.js(class2 和 class1 的父级)中调用和设置我的状态;但随后我的 Class2.js 控制台说它找不到我的状态.
  2. 我也试过:<Class1 method={this.Class2Method}/> 在我的 Class 2 和 <div onClick={this.props.method} > 在 Class1 中.

推荐答案

给你

Class1.js

       export class Class1 extends Component {
             render() {
                return (
                    <div onClick={this.props.callApi}></div>
                )
            }
       }

Class2.js

  1. 在构造函数中绑定 callApi 函数或将其更改为箭头函数.
  2. 将callApi方法作为prop传递给class1组件,在上面的组件中作为this.props.callApi访问,传递给div的onClick.

  1. Either bind callApi function in constructor or change it to arrow function.
  2. Passdown callApi method to class1 component as a prop and access it in the above component as this.props.callApi and pass it to onClick of div.

 export class Class2 extends Component {
       callApi = () => {
           Here I call my API, I set & call states, ...
        }
       render {
           return (
              <Class1 callApi={this.callApi} />
                   Here I return my API content
            )    
       }   
   }

这篇关于如何从 React.js 中的另一个类组件调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆