我试图让Shiny App工作,用户可以使用按钮或按键操作reactiveValues
。因此,最小的例子是使用向上/向下actionButton
或U / D键递增或递减计数器。用户应该能够使用这些键,而无需先点击屏幕上的任何位置。
根据此处的示例(Using enter key with action button in R Shiny,Shiny Responds to Enter和R Shiny key input binding),我想出了下面的脚本。但是,它根本不会对U / D键做出反应。按钮按预期工作。一旦我点击一个按钮,它就会变得有点"卡住了#34;我可以使用Enter键或空格键重复按钮点击,但U / D键仍无效。知道什么可能是错的吗?
这是我写的代码:
library(shiny)
shinyApp(ui <- pageWithSidebar(
headerPanel("Test keyboard control"),
sidebarPanel(
tags$script(
'tags$head(
$(document).keydown(function(e)){
if (e.keyCode == 85) {
$("#upButton").click();
} else if (e.keyCode == 68) {
$("#downButton").click();
}
});'
),
actionButton("downButton", "Down"),
actionButton("upButton", "Up")
),
mainPanel(htmlOutput("text"))
),
server <- function(session, input, output) {
vals <- reactiveValues(count = 0)
observeEvent(input$downButton, {vals$count <- vals$count - 1})
observeEvent(input$upButton, {vals$count <- vals$count + 1})
output$text <- renderText(paste("Counter is:", vals$count))
}
)
答案 0 :(得分:3)
问题在于输入事件仅捕获按下的键的键码,一旦按下键,键码保持不变。然而,只有在事件数据发生变化时才会产生反应。您需要每次都将事件数据设置为新的;例如当前的时间戳。看看这个工作示例:
library(shiny)
shinyApp(ui <- pageWithSidebar(
headerPanel("Test keyboard control"),
sidebarPanel(
tags$script('$(document).on("keydown",
function (e) {
if(e.which == 68) {
Shiny.onInputChange("downButton", new Date());
} else if (e.which == 85) {
Shiny.onInputChange("upButton", new Date());
}
});
'),
actionButton("downButton", "Down"),
actionButton("upButton", "Up")
),
mainPanel(htmlOutput("text"))
),
server <- function(session, input, output) {
vals <- reactiveValues(count = 0)
observeEvent(input$downButton, {vals$count <- vals$count - 1})
observeEvent(input$upButton, {vals$count <- vals$count + 1})
output$text <- renderText(paste("Counter is:", vals$count))
}
)