【问题标题】:Enabling and then disabling reactive events based on user input根据用户输入启用然后禁用反应事件
【发布时间】:2019-06-03 16:54:23
【问题描述】:

我正在尝试创建一个允许用户搜索自定义术语的应用程序,我试图创建的逻辑是用户,输入一个字符串,然后在键盘上按 ENTER,执行搜索词,这是可以实现的。但是在下面的示例中,按下回车按钮后,它会在文本输入中执行所有更改

我尝试将最后一个键重置为空等,但没有运气解决这个小问题,下面的简化代码

library(shiny)


ui <- fluidPage(

   # Application title
   titlePanel("example"),

   fluidRow( 
     column( 3, offset = 1,
             tags$script(' $(document).on("keydown", function (e) {
                                                  Shiny.onInputChange("lastkeypresscode", e.keyCode);
                                                  });
                                                  '),
     textInput("searchtext", 
               label = "Text input",
               value = "")),
     column( 4, textOutput("mysearch")),
     column( 4) 
    )



server <- function(input, output) {
  observe({
    if(!is.null(input$lastkeypresscode)){
      if(input$lastkeypresscode == 13){
         output$mysearch <- renderText(input$searchtext)

      }
    }
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

预期的输出是只有在按下 ENTER 键后才能在输出的文本中看到更改

【问题讨论】:

    标签: shiny


    【解决方案1】:

    您可以将onKeyPress 事件处理程序附加到文本输入:

    library(shiny)
    
    textInput2 <- function(inputId, label, value = "", width = NULL, placeholder = NULL){
      input <- textInput(inputId, label, value, width, placeholder)
      input$children[[2]] <- 
        htmltools::tagAppendAttributes(
          input$children[[2]], 
          onKeyPress = sprintf("Shiny.setInputValue('%s_keypress', event.key)", inputId))
      input
    }
    
    ui <- fluidPage(
      textInput2("textinput", "Enter text:"),
      textOutput("textoutput")
    )
    
    server <- function(input, output){
      observeEvent(input[["textinput_keypress"]], {
        if(input[["textinput_keypress"]] == "Enter"){
          output[["textoutput"]] <- renderText({
            input[["textinput"]]
          })
        }
      })
    }
    
    shinyApp(ui, server)
    

    有人说不建议在观察者内部定义output。为避免这种情况,您可以这样做:

    server <- function(input, output){
    
      Text <- eventReactive(input[["textinput_keypress"]], {
        req(input[["textinput_keypress"]] == "Enter")
        input[["textinput"]]
      })
    
      output[["textoutput"]] <- renderText({
        Text()
      })
    
    }
    

    或者,请参阅this answer。但我认为现在的答案更好。


    编辑

    OP 声称不起作用。也许更强大的解决方案是:

    onKeyPress = sprintf("Shiny.setInputValue('%s_keypress', event.which)", inputId)
    

    替换

    input[["textinput_keypress"]] == "Enter"
    

    input[["textinput_keypress"]] == 13
    

    【讨论】:

    • 嗨@Stéphane Laurent,我运行了你提供的代码,我看到了带有 Enter text: 框的屏幕,我输入了一个搜索词,然后按了 Enter 键,没有任何反应。
    • 你好@Pythonuser。请看我的编辑,它有效吗?您是否在 RStudio 浏览器中打开该应用程序?这个浏览器有问题。最好使用真正的浏览器,比如 Chrome。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多