假设我有一个最小的工作示例,如下所示
library(shiny)
library(shinyTree)
ui <- fluidPage(
shinyTree("tree", contextmenu = TRUE, search = TRUE, unique = TRUE, sort = TRUE)
)
server <- function(input, output, session) {
output$tree <- renderTree({
list(
root1 = "",
root2 = list(
SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
SubListB = list(leafA = "", leafB = "")
),
root3 = list(
SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
SubListB = list(leafA = "", leafB = "")
)
)
})
}
shinyApp(ui, server)它会生成一个类似于shinyTree (jstree)的

当我展开树时,如果我点击左边的一个小三角形(不一定选择任何东西),可以运行一个函数吗?我在考虑将shinyjs包与onclick事件一起使用,但实际上并没有管理那么多
发布于 2021-09-20 18:06:19
您可以使用jstree events 来触发一个闪亮的观察者来执行函数。在下面的示例中,JS代码将使用展开的节点的名称更新input$expanded_node的值,然后触发关联的观察者。
library(shiny)
library(shinyTree)
ui <- fluidPage(
shinyTree("tree", contextmenu = TRUE, search = TRUE, unique = TRUE, sort = TRUE),
tags$script(HTML('
// "triggered when a node is opened and the animation is complete"
$("#tree").on("after_open.jstree", function (e, data) {
Shiny.onInputChange("expanded_node", data.node.text, {priority: "event"});
});
')),
verbatimTextOutput("function_result")
)
server <- function(input, output, session) {
output$tree <- renderTree({
list(
root1 = "",
root2 = list(
SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
SubListB = list(leafA = "", leafB = "")
),
root3 = list(
SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
SubListB = list(leafA = "", leafB = "")
)
)
})
result <- reactiveValues()
observeEvent(input$expanded_node, {
# execute a function ...
result$data <- runif(1, 1, 1e6)
result$node <- input$expanded_node
})
output$function_result <- renderPrint({
paste("Node:", result$node, ", Result:", result$data)
})
}
shinyApp(ui, server)https://stackoverflow.com/questions/69258124
复制相似问题