【发布时间】: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