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

时间:2016-12-09 13:33:58

标签: r shiny shinyjs shinytree

我正在尝试隐藏和显示基于文件夹选择的按钮.Scenario是用户选择文件夹然后显示按钮,否则应隐藏按钮。我尝试使用 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)

您能否建议在此段代码中进行错误或修改以启用隐藏和显示功能。

1 个答案:

答案 0 :(得分:1)

您需要添加useShinyjs()行来设置您的闪亮应用以使用shinyjs。之后唯一的事就是默认隐藏按钮。然后在模式“leaf”出现在get_selected(输入$ 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)