ReactJS - 从另一个组件调用一个组件方法

标签 reactjs class methods call

我有两个组件。我想从第二个组件调用第一个组件的方法。我该怎么做?

这是我的代码。

第一个组件

class Header extends React.Component{

    constructor(){
        super();
    }

    checkClick(e, notyId){
       alert(notyId);
    }
}

export default Header;

第二个组件

class PopupOver extends React.Component{

    constructor(){
        super();
        // here i need to call Header class function check click....
        // How to call Header.checkClick() from this class
    }

    render(){
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
}

export default PopupOver;

最佳答案

你可以做这样的事情

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

使用静态

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

关于ReactJS - 从另一个组件调用一个组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39119537/

相关文章:

reactjs - 以下模块无法热更新 : (Full reload needed)

class - 在 drupal 8 的标题区域中添加自定义类

java - boolean allLess(int[]一,int[]二)方法

c# - 在整个类中使用创建的对象

python - 如何在python的派生类中调用同名方法的基类方法?

reactjs - Webpack 返回 ValidationError : CSS Loader Invalid Options

reactjs - react : updating one item of the list (setState) instead of all

javascript - 聚焦时如何使用 Reactjs 选择输入中的所有文本?

java - 用一种方法创建一个类是否合适?

c++ - 我可以在 C++ 中使用智能指针作为类成员吗?