下面的应用程序包含一个shinyTree
,一个重置按钮(Reset nodes
)和一个打印输出“选定的节点”。打印输出打印get_selected
函数的输出,该函数返回所选节点的列表。
这是启动时树的屏幕截图:
未选择任何节点,因此get_selected
返回一个空的list()
当我进行选择时,例如节点a
,get_selected
会正确返回该选择:
当我单击Reset nodes
时,将在树UI中清除节点选择,但是get_selected
不会与先前的选择保持不变:
单击重置按钮后,观察者将通过updateTree
更新树,如下所示:
observeEvent(input$reset, {
updateTree(session,"tree", data = tree)
})
我希望get_selected
返回list()
时会重设。我使用的是updateTree
吗?
以下是复制以上代码的代码:
library(shiny)
library(shinyTree)
tree = structure(list(a=list(a1=1,a2=2) , b="b"), stopened = T)
tree = lapply(tree, function(x) structure(x, stopened = T))
ui <- fluidPage(
tags$head(tags$script('
$("#reset").onlick(function() {
$("#tree").jstree("deselect_all");
}
')),
fluidPage(
sidebarLayout(
sidebarPanel(
actionButton('reset', 'Reset nodes')
),
mainPanel(
shinyTree("tree", ),
hr(),
"Selected nodes:",
verbatimTextOutput("idSelected")#,
)
)
)
)
# server
server <- function(input, output, session) {
output$tree = renderTree({
tree
})
output$idSelected <- renderPrint({
str(get_selected(input$tree, format = "classid"))
})
# An observer is used to trigger a tree update when reset is clicked.
observeEvent(input$reset, {
updateTree(session,"tree", data = tree)
print(get_selected(input$tree, format = "classid"))
})
}
shinyApp(ui, server)
我尝试了以下JQuery无济于事:
$("#reset").onlick(function() {
$("#tree").jstree("deselect_all");
}
答案 0 :(得分:2)
您可以点击重置按钮来更新reactiveVal
,而不是直接引用get_selected
提供的数据:
library(shiny)
library(shinyTree)
tree <- lapply(structure(list(a=list(a1=1,a2=2) , b="b"), stopened = TRUE) , function(x) structure(x, stopened = TRUE))
ui <- fluidPage(
fluidPage(
sidebarLayout(
sidebarPanel(
actionButton('reset', 'Reset nodes')
),
mainPanel(
shinyTree("tree", ),
hr(),
"Selected nodes:",
verbatimTextOutput("idSelected")#,
)
)
)
)
server <- function(input, output, session) {
treeSelection <- reactiveVal(list())
output$tree = renderTree({
tree
})
observeEvent(input$reset, {
updateTree(session, "tree", data = tree)
treeSelection(list())
})
observeEvent(input$tree, {
treeSelection(get_selected(input$tree, format = "classid"))
})
output$idSelected <- renderPrint({
treeSelection()
})
}
shinyApp(ui, server)