javascript - 从函数子组件调用类中的回调函数时,React 'this' undefined

标签 javascript reactjs

我有一个类组件作为父组件,一个功能组件作为该类组件的子组件。我将回调函数作为 Prop 传递给 child ,但是当我调用它时,我收到类型错误:

"TypeError: this.setState is not a function"

在父函数中。

关于如何解决这个问题有什么想法吗?

[编辑] 代码示例。

父组件:

import React, { Component } from 'react';

class NotificationsLayout extends React.Component {
    editConfigCompleted() {
        this.setState({
            templateDataChangedForTasksComponent: true,
            templateDataChangedForTemplatesComponent: true
        })
        this.closeEditConfigModal();
    }

    render() {        
        return (
            <div className="animated fadeIn">
                <RecipientConfigEditor completionAction={this.editConfigCompleted} />
            </div>
        )
    }
}

export default NotificationsLayout;

子组件:

import React, { useState, useEffect, useContext } from 'react';

export default function RecipientConfigEditor(completionAction) {

    function handleButtonClick() {
        completionAction();
    }

    return (
        <button onClick={handleButtonClick}></button>
    )
});

最佳答案

在构造函数中绑定(bind)

import React, { Component } from "react";
import RecipientConfigEditor from '....wherever';

class NotificationsLayout extends Component {
  constructor(props) {
    super(props);
    this.editConfigCompleted = this.editConfigCompleted.bind(this);
  }

  editConfigCompleted() {
    this.setState({
      templateDataChangedForTasksComponent: true,
      templateDataChangedForTemplatesComponent: true
    });
    this.closeEditConfigModal();
  }

  render() {
    return (
      <div className="animated fadeIn">
        <RecipientConfigEditor completionAction={this.editConfigCompleted} />
      </div>
    );
  }
}

export default NotificationsLayout;

或者设置回调时绑定(bind)

import React, { Component } from "react";
import RecipientConfigEditor from '....wherever';

class NotificationsLayout extends Component {
  editConfigCompleted() {
    this.setState({
      templateDataChangedForTasksComponent: true,
      templateDataChangedForTemplatesComponent: true
    });
    this.closeEditConfigModal();
  }

  render() {
    return (
      <div className="animated fadeIn">
        <RecipientConfigEditor completionAction={this.editConfigCompleted.bind(this)} />
      </div>
    );
  }
}

export default NotificationsLayout;

关于javascript - 从函数子组件调用类中的回调函数时,React 'this' undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807746/

相关文章:

javascript - onClick 由变量填充而不触发它

javascript - Laravel 5.2 忘记密码的模态弹出窗口显示 500 内部服务器运行 ajax 功能时出错

javascript - 仅使用 DomDocument 拉取 HREF

javascript - three.js - 用于 ipad 的管几何结构上的 Canvas 纹理

javascript - Angular 旋转器 : functions execution order

javascript - 为什么 this.props.children.map 不起作用?

javascript - 在 Gatsby.js 中以编程方式创建多种类型的页面

javascript - 将 ES6 类转换为 Typescript 类

javascript - 在 Material-UI 选项卡中使用分隔线

javascript - 有条件地禁用父级的子级按钮 - React