我有一个类组件作为父组件,一个功能组件作为该类组件的子组件。我将回调函数作为 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/