我正在创建一个闪亮的应用程序,并意识到我正在重复一个特定的UI元素,所以我想知道是否存在一种将其包装在函数中并提供参数以使其在不同情况下工作的方法。在我的服务器文件中,我有
output$loss <- renderUI({
req(input$got)
if(input$got %in% Years) return(numericInput('got_snow', label = 'John Snow', value = NA))
if(!input$got %in% Years) return(fluidRow(column(3)))
})
并且在ui文件中,我有:
splitLayout(
cellWidths = c("30%","70%"),
selectInput('got', label = 'Select age', choices = c('',Years) , selected = NULL),
uiOutput("loss")
)
由于我发现自己使用了几次,并且只更改了UI和服务器文件中的一些内容,所以我想将它们包装在一个函数中,并在需要时使用它们。我为服务器文件尝试过此操作
ui_renderer <- function(in_put, label, id){
renderUI({
req(input[[in_put]])
if(input[[in_put]] %in% Years) return(numericInput(id, label = label, value = NA))
if(!input[[in_put]] %in% Years) return(fluidRow(column(3)))
})
}
output$p_li <- ui_renderer(input='li', "Enter age", id="c_li")
并且放在我的ui文件中
uiOutput('c_li')
但是它不起作用。非常感谢您的帮助。
由于没有最少的工作示例,因此我无法测试您的代码。我不知道您的示例中是否有错字,但是您正在尝试渲染c_li
,但是您的输出称为p_li
。不知道如何将渲染对象包装到标准函数中,但是我已经使用反应性值进行了类似的操作。
这是使用您的某些术语的最小示例。这不是一个可行的示例,而是我提出的解决方案的构想概述。
# Set up the UI ----
ui <- fluidPage(
uiOutput("loss")
)
# Set up the server side ----
server <- function(input, output, session) {
# Let us define reactive values for the function inputs
func <- reactiveValues(
value <- "got",
label <- "select age",
id <- "xyz"
)
# Set up an observer for when any of the reactive values change
observeEvent({
func$value
func$label
func$id
}, {
# Render a new UI any time a reactive value changes
output[["loss"]] <- renderUI(
if (input[[func$value]] %in% years) {
numericInput(func$id, label = func$label, value = NA)
} else {
fluidRow(
column(3)
)
}
)
})
}
# Combine into an app ----
shinyApp(ui = ui, server = server)
一般想法是定义一组反应性值并设置一个观察器,该观察器将在每次一个或多个反应性值更改时呈现UI。您可以使用直接分配将新值分配给任何无功值,例如current$value <- "object_two"
。进行更改将使用Shiny的反应模式更新UI,这意味着您只需更改一个值即可更新UI。