【问题标题】:React 'this' undefined when calling a callback function in a class from a function child component [duplicate]从函数子组件调用类中的回调函数时反应“this”未定义[重复]
【发布时间】:2020-05-05 13:05:12
【问题描述】:

我有一个类组件作为父类组件和一个功能组件作为类组件的子类。我将一个回调函数作为道具传递给孩子,但是当我调用它时,我得到一个类型错误:

"TypeError: this.setState 不是函数"

在父函数中。

关于如何解决这个问题的任何想法?

[编辑] 代码示例。

父组件:

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>
    )
});

【问题讨论】:

  • 你能分享有问题的代码吗?可能您需要正确定义回调函数才能将父组件的this 绑定到它。
  • 你在Parent的构造函数中绑定了回调吗?
  • 在将回调函数传递给子组件之前,您需要将回调函数与您的类组件绑定

标签: javascript reactjs


【解决方案1】:

在构造函数中绑定

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;

或设置回调时绑定

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;

【讨论】:

  • 这行得通。谢谢老哥!
猜你喜欢
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多