简体   繁体   English

conditionalPanel 和 uiOutput/req 模式之间的区别

[英]Difference between conditionalPanel and uiOutput/req patterns

Consider the below sample application demonstrating two ways to show UI based on a condition:考虑下面的示例应用程序,演示了两种基于条件显示 UI 的方法:

library(shiny)

ui <- fluidPage(
  tagList(
    checkboxInput("toggle", "Toggle"),
    conditionalPanel(
      condition = "output.condition",
      tags$p("Output from conditionalPanel")
    ),
    uiOutput("ui")
  )
)

server <- function(input, output, session) {
        
  # conditionalPanel
  output$condition <- reactive(input$toggle)
  outputOptions(output, "condition", suspendWhenHidden = FALSE)
  
  # uiOutput
  output$ui <- renderUI({
    req(isTRUE(input$toggle))
    tags$p("Output from uiOutput")
  })
  
}

shinyApp(ui, server)

In terms of the front-end, the conditionalPanel and uiOutput / req patterns seem to behave similarly.在前端方面, conditionalPaneluiOutput / req模式的行为似乎相似。 Are there any differences, especially related to performance, that would make one pattern more beneficial?是否有任何差异,特别是与性能相关的差异,会使一种模式更有益?

These two ways do have different purposes .这两种方式确实有不同的目的 conditionalPanel creates a JavaScript expression which "listens" for a specific condition, eg whether an input is TRUE or FALSE . conditionalPanel创建一个 JavaScript 表达式,它“侦听”特定条件,例如输入是TRUE还是FALSE Nothing needs to happen on the server-side.服务器端不需要发生任何事情。

renderUI() in contrast is very flexible.相比之下, renderUI()非常灵活。 Of course, it can mimic the behavior of conditionalPanel but is also capable to output basically anything by creating different HTML (UI) code.当然,它可以模仿conditionalPanel的行为,但也可以通过创建不同的 HTML (UI) 代码来实现 output 基本上任何事情。

Regarding speed: conditionalPanel should almost always be faster.关于速度: conditionalPanel应该几乎总是更快。 Additionally, not performance should be the decider between both options but the goal should.此外,不是性能应该是两个选项之间的决定因素,而是目标应该。

example app示例应用

library(shiny)

ui <- fluidPage(
  tagList(
    checkboxInput("toggle", "Toggle"),
    conditionalPanel(
      # listens whether toggle is TRUE or FALSE
      condition = "input.toggle",
      tags$p("Output from conditionalPanel")
    ),
    uiOutput("ui")
  )
)

server <- function(input, output, session) {

  # create a plot
  output$myplot <- renderPlot({
    plot(mtcars$mpg, mtcars$cyl)
  })

  # create some text
  output$mytext <- renderText({
    "I am pointless"
  })


  # uiOutput
  output$ui <- renderUI({
    input$toggle
    if (rnorm(1) > 0){
      plotOutput("myplot")
    } else {
      textOutput("mytext")
    }
  })

}

shinyApp(ui, server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM