Shiny 提供了一个包装 selectize.js
的 selectizeInput
,它会生成一个文本输入/组合框小部件。我想延迟加载 selectizeInput 的选项/值有几个原因:可能有很长的值列表,或者可能的值取决于其他参数。此外,我希望用户能够创建新值(例如,选择现有值或创建自己的值)。
但是在所有这些情况下,不能使用 Shiny 的服务器端书签来为 selectizeInput 的值添加书签。初始化 selectizeInput 对象时,存储在 input
中的书签值还不是有效的选项值。
有没有人有任何巧妙的解决方法来为 selectizeInput 值添加书签?
这是仅处理 create
选项的最简单示例:
library(shiny)
ui <- function(request) {
fluidPage(
selectizeInput("foo", "Created Values Cannot Be Bookmarked", choices=c("Choose From List or Type New Value"="", "bar", "baz"),
options=list(create=TRUE)),
bookmarkButton("Update URL")
)}
server <- function(input, output) {
onBookmarked(function(url) {
updateQueryString(url)
})
}
shinyApp(ui = ui, server = server, enableBookmarking = "server")
如果您在选择框中键入新值,点击书签按钮更新浏览器地址栏中的 URL,然后点击重新加载,则创建的值将会丢失。尝试对现有选项进行同样的操作,当然可以。
如果延迟加载选项会变得更复杂,但问题是一样的,即在 selectizeInput
渲染时用户的选择无效。
最佳答案
这是一个更好的解决方案,它使用服务器端支持 selectize。支持 create=TRUE
选项的重要步骤是使用 onRestored
使用用户创建的新值更新选项。
library(shiny)
init.choices <- c("Choose From List or Type New Value"="")
ui <- function(request) {
fluidPage(
titlePanel("Bookmarking Created Values"),
selectizeInput("foo", NULL,
choices=init.choices,
multiple=TRUE,
options=list(create=TRUE)),
bookmarkButton("Update URL")
)}
server <- function(input, output, session) {
updateSelectizeInput(session, "foo", choices=c(init.choices, rownames(mtcars)), server=TRUE)
onBookmarked(function(url) {
updateQueryString(url)
})
onRestored(function(state) {
updateSelectizeInput(session, "foo", selected=state$input$foo, choices=c(init.choices, rownames(mtcars), state$input$foo), server=TRUE)
})
}
shinyApp(ui = ui, server = server, enableBookmarking = "server")
关于shiny - 如何使用动态选项为 Shiny selectizeInput 添加书签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723322/