如何从React.js中的另一个类组件调用方法

Céd*_*oem 5 methods components class reactjs

因此,我必须对组件进行分类:
Class1:具有一个单击按钮
Class2:具有一种调用我的api的方法

基本上,我想要的是调用一个方法来设置和编辑来自另一个类的一个类内的状态。但是我一直失败。

例:

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
      )    
   }   
}
Run Code Online (Sandbox Code Playgroud)

我试过的

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

Hem*_*ari 6

干得好

Class1.js

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

Class2.js

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

     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
                )    
           }   
       }
    
    Run Code Online (Sandbox Code Playgroud)


Luk*_*ker 6

我如何从 react.js 中的另一个类组件调用方法

使用道具

“render prop”是指一种在 React 组件之间共享代码的技术,使用一个值是一个函数的 prop” - reactjs.org

例子

应用程序.js

import Button from '../../pathtoButton';
export class App extents Component {
    constructor(props){
        super(props)
        this.state = {
             name:'John'
        }
    }
    sayHello(){
        const { name } = this.message;
        alert(`Hello ${name}`}
    }
    render(){
        return (
             <div>
                 <Button
                     value="click me"
                     whenClicked={this.sayHello}
             </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

按钮.js

export class Button extents Component {
    constructor(props){
        super(props)
        this.state = {
             style:{background:'red', color:'white'},
        }
    }
    render(){
        const { style } = this.state;
        const { whenClicked, value} = this.props;
        return (
             <div>
                 <button style={style} onClick={whenClicked}>{value}</button>
             </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

解释

app.js我们导入组件<Button/>并使用props我们将一个方法从app.js" sayHello"传递到我们创建的名为whenClicked. 在button.js我们引用this.props.whenClicked并将其传递给onClick属性。

sayHello现在在两个组件之间共享,因为我们将方法作为 prop 传递给<Button/>组件。