【发布时间】:2017-11-30 12:57:57
【问题描述】:
我在 Shiny 的书签中遇到了小问题(可能是错误?) - 我动态创建 UI - 新的文本和数字输入。这些输入是通过单击 ActionButton 创建的。保存书签 URL 时 - 数字和文本输入的值都在此 URL 中。到目前为止,一切都很好。然而,在加载保存的 URL 后,我只看到了第一个动态创建的 UI。我必须单击操作按钮才能添加下一个数字和文本输入。这些值保存在 URL 中,一旦添加了这些输入,它们就会填充正确的保存值。但是,如果您有 20 个这样的按钮并且您必须单击 19 次才能将它们全部显示在屏幕上,那就有点不方便了。 这是一个简短的可重现示例。
library(shiny)
ui <- function(request){
shinyUI(fluidPage(
bookmarkButton(),
sidebarLayout(
actionButton('addElement', 'Add Element', icon("plus"), class="btn-success text-white"),
mainPanel(
id ="content"
)
)
))
}
shinyServer(function(input, output) {
enableBookmarking("url")
countvar <<- 0
observeEvent(input$addElement, {
countvar <<- countvar + 1
element <- paste0("var", countvar)
insertUI(
selector = "#content",
where = "beforeEnd",
ui = tagList(
wellPanel(
style = "display:-webkit-inline-box;width:100%",
id = element,
column(3,
textInput(element, "Element name")
),
column(3,
numericInput(paste0(element, "Value"), "Element Value", NULL)
)
)
)
)
})
})
我在 SO 上发现了类似的问题,遗憾的是没有答案 - Shiny app bookmarking: dynamic UI input lost
【问题讨论】:
-
您需要使用
onRestore()函数。看看这篇文章:shiny.rstudio.com/articles/advanced-bookmarking.html -
嗨,芭芭拉,感谢您的链接。我想我知道问题出在哪里——即使在 URL 中 addElement 的值大于 1,它也只会触发一次。但是我不确定如何将
onRestore()函数合并到我的代码中。我到底应该调用什么 - 触发代码的“observeElement”部分?还是简单地解析纯 HTML?谢谢,我现在有点迷路了。