Вы можете прикрепить обработчик события 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()
})
}
В качестве альтернативы см. этот ответ .Но настоящий ответ, я думаю, лучше.
РЕДАКТИРОВАТЬ
ОП утверждает, что не работает.Возможно, более надежное решение:
onKeyPress = sprintf("Shiny.setInputValue('%s_keypress', event.which)", inputId)
и замените
input[["textinput_keypress"]] == "Enter"
на
input[["textinput_keypress"]] == 13