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

I have two components. I want to call a method of the first component from the second component. How can I do it?

Here is my code.

First Component

class Header extends React.Component{

    constructor(){
        super();
    }

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

export default Header;

Second Component

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;
解决方案

You can do something like this

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;

Using statics

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

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

我有两个组成部分。我想从第二个组件中调用第一个组件的方法。我该怎么办?



这是我的代码。



第一个组件



 类头扩展了React.Component {

Constructor(){
super() ;
}

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

导出默认标题;


第二部分



 类PopupOver扩展了React.Component {

Constructor(){
super();
//在这里,我需要调用Header类函数check click ....
//如何从此类中调用Header.checkClick()
}

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

导出默认值PopupOver;

解决方案

您可以执行以下操作



  import从'react'进行反应; 

类标题扩展了React.Component {

Constructor(){
super();
}

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

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

}
};

类PopupOver扩展了React.Component {

构造函数(props){
super(props ;;
this.props.func(this,1234);
}

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

导出默认标题;


使用静态变量



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

MyComponent.customMethod(’bar’); // true
原文地址:https://www.cnblogs.com/shaozhu520/p/12922233.html