reactjs - 子类组件调用父类组件的方法
问题描述
我在 App.js 中有一个addNotification()方法,我想在我的其他一些组件中重用它。这里我以AgencyProfile组件为例。如果我从App.js导出addNotification()方法,它将不起作用。如何从其他子组件调用方法addNotification(),例如AgencyProfile?这是我的 App.js 代码
export class App extends React.Component{
.....
addNotification(title, message, level, time) {
let dismiss = (time === undefined) ? 0 : time;
this.notification.addNotification({
title: title,
message: message,
level: level,
autoDismiss: dismiss
});
}
.......
render() {
return (
<div>
<NotificationSystem ref={ref => this.notification = ref}/>
<AgencyProfile />
</div>
);
}
}
解决方案
是的,如果您将函数addNotification
作为要在其中重用函数的组件的道具(回调)传递,这是可能的:
应用程序.js:
export class App extends React.Component{
.....
addNotification = (title, message, level, time) => {
let dismiss = (time === undefined) ? 0 : time;
this.notification.addNotification({
title: title,
message: message,
level: level,
autoDismiss: dismiss
});
};
.......
render() {
return (
<div>
<NotificationSystem ref={ref => this.notification = ref}/>
<AgencyProfile onAddNotification={this.addNotification} />
.....
</div>
);
}
}
在子组件中,我们可以像这样创建一个方法来调用App.js中的addNotification()方法
AgencyProfile.js
showNotification(title, message, level, time){
this.props.onAddNotification(title, message, level, time);
}
使用此方法从AgencyProfile组件内的任何位置调用addNotification() 。
另一种方法是使addNotification()成为另一个js
文件中的可导出函数,然后将其导入要使用它的组件中(但是使用这种方法,您必须this
根据要使用它的位置进行绑定):
import addNotification from 'helpers/addNotification';
推荐阅读
- reactjs - 如何在 Reactjs 中将 CKEditor 用于数学公式和 MathJax
- php - Xampp Apache 服务器意外关闭
- numpy - 如何在numpy中对角化> 2d数组?
- google-chrome - Axios / Chrome:POST请求后出现意外的GET请求
- javascript - Chrome 扩展:ReferenceError:$ 未定义
- image - 在反应原生中调整启动画面上的图像大小
- python - Python:为什么 numpy 数组占用的内存空间比相同维度的 pandas 数据框大得多?
- amazon-web-services - 用于配置 EC2 托管 PEM 文件的 Terraform(用于 SSH)
- r - 在 R markdown 中创建一个简单的问题和答案
- swift - 在没有第二个参数的情况下在 Swift 中使用 reduce() 函数