ReactJS - 从另一个组件调用一个组件方法 [英] ReactJS - Call One Component Method From Another Component

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

问题描述

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

这是我的代码.

第一个组件

class Header 扩展 React.Component{构造函数(){极好的();}checkClick(e, notyId){警报(notyId);}}导出默认标题;

第二部分

class PopupOver 扩展 React.Component{构造函数(){极好的();//这里我需要调用 Header 类函数 check click....//如何从这个类调用 Header.checkClick()}使成为(){返回 (<div className="displayinline col-md-12 ">你好

);}}导出默认 PopupOver;

解决方案

你可以这样做

从'react'导入React;类头扩展 React.Component {构造函数(){极好的();}checkClick(e, notyId) {警报(notyId);}使成为() {返回 (<PopupOver func ={this.checkClick }/>)}};类 PopupOver 扩展了 React.Component {构造函数(道具){超级(道具);this.props.func(this, 1234);}使成为() {返回 (<div className="displayinline col-md-12 ">你好

);}}导出默认标题;

使用静态

var MyComponent = React.createClass({静态:{自定义方法:函数(foo){返回 foo === 'bar';}},渲染:函数(){}});MyComponent.customMethod('bar');//真的

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆