如何使用带有shinyjs切换功能的req()来启用/禁用元素?

时间:2018-04-24 13:31:35

标签: shiny shinyjs

如果输入至少1个字符,则下面的应用程序将正确禁用该按钮,然后启用6个或更多字符。如果没有给出任何字符,则启用该按钮,因为req(输入$ some_text)返回无提示错误。

library(shiny)
library(shinyjs)

ui <- fluidPage(
   useShinyjs(),
     textInput("some_text", "Write at least 5 characters to enable button",
               value = ""),
     actionButton("button", "A Button")
)

server <- function(input, output) {

  first_step <- reactive({
    req(input$some_text)
    stringr::str_count(input$some_text, "[0-9]") > 5
  })

  observe({
    toggleState("button", condition = first_step())
  })
}

我理解当没有输入时,toggle()没有任何工作可做。 在这种情况下,是否应该总是使用if子句?

  first_step <- reactive({
    if(input$some_text > 0){
        stringr::str_count(input$some_text, "[0-9]") > 5
    } else FALSE
  })

1 个答案:

答案 0 :(得分:0)

试试这个,请注意我在开头添加了disable

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textInput("some_text", "Write at least 5 characters (numeric) to enable button",value = ""),
  actionButton("button", "A Button")
)

server <- function(input, output) {

  first_step <- eventReactive(input$some_text,{
    disable("button")
    req(input$some_text)
    stringr::str_count(input$some_text, "[0-9]") >= 5
  })

  observeEvent(first_step(),{
    toggleState("button", condition = first_step())
  })
}

shinyApp(ui,server)

enter image description here