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

这是我的密码.

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;

推荐答案

你可以这样做

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相关问答推荐

为什么Next.js 14无法解析页面路由路径?

后端关闭时如何在REACTION AXIOS拦截器中模拟数据?

Google Firestore无法读取图像-react

使用REACT-RUTER-DOM链接仅更新一个搜索参数

获取未捕获的错误:Gatsby生产版本上的最小化react 错误#418

在动态React组件中删除事件侦听器

React Context API 在 Next.js 中更改路由时获取默认数据

从ReactDataGridtry 将数据传递给父组件

无法从子组件传递数据到父组件

redux 工具包使用中间件构建器函数时,必须返回一个中间件数组

如何在 Next Js 13 App Router 中添加 Favicon 图标?

在按钮单击中将动态参数传递给 React Query

来自一个自定义 React Native 组件的样式从另一个自定义组件移除样式

动态添加或删除文本输入字段并将值设置为 React JS 中主要状态的数组

下一次导出:未捕获的语法错误:标识符注册表已被声明

react 事件顺序

如何使用 cypress 获取 MUI TextField 的输入值?

.filter() 函数在删除函数中创建循环 - React

React LinkProps 的含义

单击按钮时获取react 表中每一行的属性