简体   繁体   English

在闪亮的应用程序中使用观察事件进行 numericInput

[英]using observeEvent for numericInput in shiny app

I have a simple shiny app which I would like to show a warning if user input is bigger than a threshold.我有一个简单的闪亮应用程序,如果用户输入大于阈值,我想显示警告。

library(shiny)
library(shinyalert)

ui <- fluidPage(
  numericInput("obs", "Observations:", 1),
  verbatimTextOutput("value")
)
server <- function(input, output) {
  observeEvent(input$obs,{
    if(!is.na(input$obs) && input$obs >10){
      shinyalert("warning!", "input too big", type = "warning")
    }
  })
  output$value <- renderText({ input$obs })
}
shinyApp(ui, server)

if user is not quick enough to provide input, let say for the input$obs = 110 we have 1 second delay between putting the second and third value the popups warning will appear !如果用户提供输入的速度不够快,假设对于input$obs = 110 ,我们在输入第二个和第三个值之间有 1 秒的延迟,弹出警告将出现! How should I fix this ?我应该如何解决这个问题?

Use shinyCatch from spsComps to make your life easier使用来自shinyCatchspsComps让您的生活更轻松

library(shiny)
library(spsComps)
ui <- fluidPage(
    numericInput("obs", "Observations:", 1),
    verbatimTextOutput("value")
)
server <- function(input, output) {
    output$value <- renderText({ 
        shinyCatch({
            if(!is.na(input$obs) && input$obs >10) warning("input too big")
        }, blocking_level = "warning", prefix = "")
        
        input$obs 
    })
}
shinyApp(ui, server)

when blocking_level = "warning" is specified shinyCatch blocks following code in the renderText expression.blocking_level = "warning"被指定时,会在renderText表达式中的代码之后出现shinyCatch块。 So when your number is larger than 10, the new input$obs will not be rendered.所以当你的数字大于 10 时,新的input$obs将不会被渲染。

Here's what users see这是用户看到的

在此处输入图像描述

Here's what developers see in the console这是开发人员在控制台中看到的内容在此处输入图像描述

You can use showNotification() from shiny itself:您可以使用闪亮本身的showNotification()

library(shiny)

ui <- fluidPage(
  numericInput("obs", "Observations:", 1),
  verbatimTextOutput("value")
)
server <- function(input, output) {
  observeEvent(input$obs,{
    if(!is.na(input$obs) && input$obs >10){
      showNotification(
        ui = tags$h4("Input Too Big!"), 
        type = "warning"
      )
    }
  })
  output$value <- renderText({ input$obs })
}
shinyApp(ui, server)

Or {shinytoastr} :{shinytoastr}

library(shiny)
library(shinytoastr)

ui <- fluidPage(
  shinytoastr::useToastr(), 
  
  numericInput("obs", "Observations:", 1),
  verbatimTextOutput("value")
)
server <- function(input, output) {
  observeEvent(input$obs,{
    if(!is.na(input$obs) && input$obs >10){
      shinytoastr::toastr_warning(
        message = "Decrease it.", 
        title = "Input too big!"
      )
    }
  })
  output$value <- renderText({ input$obs })
}
shinyApp(ui, server)

Or {spsComps} as @lz100 mentioned.或 @lz100 提到的{spsComps} The choice is yours.这是你的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM