R语言 根据闪亮应用中动态框()内小部件的值为动态框()上色

vuktfyat  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(142)

在下面的shiny应用程序中,我根据包含在box()中的sliderInput()的值给框着色。问题是,如果框没有值,它最初不会显示。

## app.R ##
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$style(HTML("
                      
                      #mybox2Red{border-top-style: none; border-left-color: red; border-left-style: solid;}
                      #mybox2Green{border-top-style: none; border-left-color: green; border-left-style: solid;}
                      "))
      ),
    
    uiOutput("box2")
      )
      )

server <- function(input, output) { 
  
  
  output$box2<-renderUI({
    req(input$vr)
    if(input$vr<=5){
      tags$style(
        type = 'text/css',
        "#mybox2Red{border-top-style: none; border-left-color: red; border-left-style: solid;}"
      )
      box(
        id="mybox2Red",
        title = "title", 
        closable = TRUE, 
        width = 10,
        status = "danger", 
        solidHeader = F, 
        collapsible = TRUE,
        collapsed = T,
        sliderInput("vr","Set value range",min = 0,max=10,value =  5)
      )
    }
    else{
      tags$style(
        type = 'text/css',
        "#mybox2Green{border-top-style: none; border-left-color: green; border-left-style: solid;}"
      )
      box(
        id="mybox2Green",
        title = "title", 
        closable = TRUE, 
        width = 10,
        status = "danger", 
        solidHeader = F, 
        collapsible = TRUE,
        collapsed = T,
        sliderInput("vr","Set value range",min = 0,max=10,value =  5)
        
      )
    }
  })
}

shinyApp(ui, server)
fxnxkyjh

fxnxkyjh1#

如果你通过一个无功值来传递这个值,这很容易做到。现在你可以在renderUI之外初始化ValueRange,这样你就可以避开这个问题。
我稍微修改了一下renderUI。使用if的方式需要维护dame代码两次。除非你打算在2个box状态中添加更多的差异,否则将来会更容易(更容易阅读)。现在条件只修改box id。但是-当然-如果它对你的想法没有意义,你可以忽略它。
请注意,由于collapsed = T,滑块的每次更新都会折叠框。

## app.R ##
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$style(HTML("
      #mybox2Red{border-top-style: none; border-left-color: red; border-left-style: solid;}
      #mybox2Green{border-top-style: none; border-left-color: green; border-left-style: solid;}
      "))
    ),
    uiOutput("box2")
  )
)

server <- function(input, output) {
  ValueRange <- reactiveVal(5)
  
  observeEvent(input$vr, ValueRange(input$vr))
  
  output$box2 <- renderUI({
    req(ValueRange)

    box(
        id=ifelse(input$vr<=5, "mybox2Red", "mybox2Green"),
        title = "title", 
        closable = TRUE, 
        width = 10,
        status = "danger", 
        solidHeader = F, 
        collapsible = TRUE,
        collapsed = T,
        sliderInput("vr","Set value range", min = 0, max=10, value =  ValueRange())
      )
  })
}

shinyApp(ui, server)

相关问题