在 R Shiny 中隐藏和显示小部件

hide and show widget in R Shiny

我正在尝试根据 文件夹选择 隐藏和显示按钮。场景是如果用户选择文件夹,则显示按钮,否则应该隐藏按钮。我并尝试使用 shinyjs 包来实现相同的目标。 这是我写的一段代码:

library(shiny)
library(shinyTree)
library(shinyjs)

ui <- shinyUI(
pageWithSidebar(
# Application title
headerPanel("shinyTree with 'selected' input"),

sidebarPanel(
  helpText(HTML("An example of using shinyTree's <code>get_selected</code> function to extract the cells which are currently selected.
                <hr>Created using <a href = \"http://github.com/trestletech/shinyTree\">shinyTree</a>.")),

  actionButton('submit','SUBMIT')

),
mainPanel(
  "Currently Selected:",
  verbatimTextOutput("selTxt"),
  hr(),
  shinyTree("tree")
)
))

server <- shinyServer(function(input, output, session) {
log <- c(paste0(Sys.time(), ": Interact with the tree to see the logs   here..."))

output$tree <- renderTree({
list(
  root1 = structure("123"),
  root2 = list(
    SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
    SubListB = list(leafA = "", leafB = "")
  )
 )
})

output$selTxt <- renderText({
tree <- input$tree
if (is.null(tree)){
  "None"
} else{
  unlist(get_selected(tree))

}})

observe({
if('leaf' %in% get_selected(input$tree)){
  shinyjs::show("submit")
}else{
  shinyjs::hide("submit")
}
})

})

shinyApp(ui, server)

能否请您提出需要在这段代码中进行的错误或修改以启用隐藏和显示功能。

您需要添加 useShinyjs() 行来设置您的 shiny 应用程序以使用 shinyjs。之后唯一的事情就是默认隐藏按钮。然后当模式 "leaf" 在 get_selected(input$tree) 返回的字符串中时显示它。 这是你想要的吗?

library(shiny)
library(shinyTree)
library(shinyjs)

ui <- shinyUI(
  pageWithSidebar(
    # Application title

    headerPanel("shinyTree with 'selected' input"),

    sidebarPanel(
      helpText(HTML("An example of using shinyTree's <code>get_selected</code> function to extract the cells which are currently selected.
                    <hr>Created using <a href = \"http://github.com/trestletech/shinyTree\">shinyTree</a>.")),

      actionButton('submit','SUBMIT')

    ),
    mainPanel(
      useShinyjs(),
      "Currently Selected:",
      verbatimTextOutput("selTxt"),
      hr(),
      shinyTree("tree")
    )
  ))

server <- shinyServer(function(input, output, session) {
  log <- c(paste0(Sys.time(), ": Interact with the tree to see the logs   here..."))
  shinyjs::hide("submit")
  output$tree <- renderTree({
    list(
      root1 = structure("123"),
      root2 = list(
        SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
        SubListB = list(leafA = "", leafB = "")
      )
    )
  })

  output$selTxt <- renderText({
    tree <- input$tree
    if (is.null(tree)){
      "None"
    } else{
      unlist(get_selected(tree))

    }})

  observe({
    if(!is.null(unlist(get_selected(input$tree)))){
      if(length(unlist(strsplit(unlist(get_selected(input$tree)),"leaf")))>1){
        shinyjs::show("submit")
      }else{
        shinyjs::hide("submit")
      }
    }

  })

})

shinyApp(ui, server)