r - 使用一个 if() 而不是多个 observeEvent() 在闪亮的应用程序中显示消息
问题描述
我在下面有一个闪亮的应用程序,其中我使用了三个基于操作按钮激活的观察者。我想知道如何用包含所有 3 个条件的 if() 替换这些观察者。
library(shiny)
library(shinyWidgets)
ui <- fluidPage(
tags$h2("Sweet Alert examples"),
actionButton(
inputId = "success",
label = "Launch a success sweet alert",
icon = icon("check")
),
actionButton(
inputId = "error",
label = "Launch an error sweet alert",
icon = icon("remove")
),
actionButton(
inputId = "sw_html",
label = "Sweet alert with HTML",
icon = icon("thumbs-up")
)
)
server <- function(input, output, session) {
observeEvent(input$success, {
sendSweetAlert(
session = session,
title = "Success !!",
text = "All in order",
type = "success"
)
})
observeEvent(input$error, {
sendSweetAlert(
session = session,
title = "Error !!",
text = "It's broken...",
type = "error"
)
})
observeEvent(input$sw_html, {
sendSweetAlert(
session = session,
title = NULL,
text = tags$span(
tags$h3("With HTML tags",
style = "color: steelblue;"),
"In", tags$b("bold"), "and", tags$em("italic"),
tags$br(),
"and",
tags$br(),
"line",
tags$br(),
"breaks",
tags$br(),
"and an icon", icon("thumbs-up")
),
html = TRUE
)
})
}
shinyApp(ui, server)
解决方案
你可以在得到事件后调用一个辅助函数来做你想做的事
server <- function(input, output, session) {
observeEvent(input$success, {sendMessage("success")})
observeEvent(input$error, {sendMessage("error")})
observeEvent(input$sw_html, {sendMessage("sw_html")})
sendMessage <- function(type) {
if (type=="success") {
sendSweetAlert(
session = session,
title = "Success !!",
text = "All in order",
type = "success"
)
} else if (type=="error") {
sendSweetAlert(
session = session,
title = "Error !!",
text = "It's broken...",
type = "error"
)
} else if (type="sw_html") {
sendSweetAlert(
session = session,
title = NULL,
text = tags$span(
tags$h3("With HTML tags",
style = "color: steelblue;"),
"In", tags$b("bold"), "and", tags$em("italic"),
tags$br(),
"and",
tags$br(),
"line",
tags$br(),
"breaks",
tags$br(),
"and an icon", icon("thumbs-up")
),
html = TRUE
)
}
}
}
推荐阅读
- ios - Swift 应用程序上的 AVPlayer 显示黑屏,但在播放视频时播放音频
- java - 当所有步骤都已完成时,Spring 批处理作业状态失败
- python - 如何抓取网站正文内容以确认字符串是否存在
- perl - Perl 不一致地打印包含 '%' 特定组合的字符串
- electron - 如何在 forge.config.js 中配置两个不同的渲染器进程?
- c++ - 头文件似乎在 .lib 库中定义了它的枚举
- javascript - 如何让primeng的确认服务等待用户的同意或拒绝?
- python - 读取帧python时无法限制每秒帧数
- hyperledger-fabric - Hyperledger Fabric - 更改 max_message_count 配置更新“错误验证增量集”以下教程
- azure - 如何在 velero 部署上运行 helm upgrade?