javascript - 如何根据按钮的点击事件提供此功能的不同道具?
问题描述
我正在尝试重用一个函数来在 Ionic 4 中打开一个模态。这两者虽然是分开的,但更愿意根据它们的独立参数进行组合,以更改出现的模态中的标题。
这不会编译,但显示了我本质上想要实现的目标:
async openModal(edit, add) {
const modal = await this.modalController.create({
component: ModalComponent,
componentProps: {
if (edit) {
'title': 'Edit Firehouse'
else if (add) {
'title': 'Add Firehouse'
},
'firehouseShow': true
}
});
return await modal.present();
}
这是当前的内容,即使出现错误也可以编译:
'重复的功能实现。
async openModal(edit) {
const modal = await this.modalController.create({
component: ModalComponent,
componentProps: {
'title': 'Edit Firehouse',
'firehouseShow': true
}
});
return await modal.present();
}
async openModal(add) {
const modal = await this.modalController.create({
component: ModalComponent,
componentProps: {
'title': 'AddFirehouse',
'firehouseShow': true
}
});
return await modal.present();
}
这些函数是通过 Angular 按钮单击事件调用的:
<ion-button (click)="openModal(edit)">Edit</ion-button>
<ion-button (click)="openModal(add)">Add</ion-button>
我更愿意重用这个函数,特别是因为它只在一个页面上(一次)被调用。但是,它确实会动态更改模式中显示的内容以及每次点击事件填充或不填充的数据。例如,“添加”点击事件不会检索任何数据,但“编辑”会。
解决方案
即使解决了重复功能问题,第二个也无法工作,因为两个功能都做同样的事情。
考虑传递componentProps
as 参数。
async openModal(componentProps) {
const modal = await this.modalController.create({
component: ModalComponent,
componentProps
});
return await modal.present();
}
当调用一个函数时:
openModal({
'title': 'Edit Firehouse',
'firehouseShow': true
})
// or
openModal({
'title': 'Add Firehouse',
'firehouseShow': true
})
更新
如果您只想获取标题作为参数,请在创建对象时设置标题。
async openModal(title) {
const modal = await this.modalController.create({
component: ModalComponent,
componentProps : {
'title': title,
'firehouseShow': true
}
});
return await modal.present();
}
接着:
openModal('Edit Firehouse')
// or
openModal('Add Firehouse')
推荐阅读
- python - 检查语音频道中的人是否打开了视频(discord.py)
- excel - 尝试计算 Col1 匹配的 Col2 值
- android - 如何使用 androidpublisher 为一个 APK 上传两个反混淆文件?
- python - 使用 numpy.where 创建掩码
- node.js - 同时运行 npm
- python-3.x - 如何根据数据框的索引绘制多条线?
- java - java - 如何在java中将一个字符串分隔为多个json对象?
- python-3.x - 在 python 中可视化 XGBoost。叶混淆输出
- applet - 小程序在同一会话中复制
- c# - Swashbuckle 仅向某些方法添加自定义标头