You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Shiny应用的JSTree中实现子节点继承父节点属性

解决R Shiny中JSTree子节点继承父节点属性的问题

修改思路

在拖拽生成子节点的回调逻辑中,不再仅生成带序号的文本节点,而是复制父节点的样式、状态、图标等核心属性,确保子节点和父节点样式一致。

修改后的完整代码

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$head(
    tags$script(HTML("
      $(document).ready(function() {
        $('#jstree').jstree({
          'core': {
            'check_callback': true,
            'data': [
              {
                'text': '父节点1',
                'icon': 'glyphicon glyphicon-folder-open',
                'state': {'opened': true},
                'li_attr': {'style': 'color: #2ecc71; font-weight: bold;'},
                'children': []
              },
              {
                'text': '父节点2',
                'icon': 'glyphicon glyphicon-file',
                'state': {'opened': false},
                'li_attr': {'style': 'color: #3498db; font-style: italic;'},
                'children': []
              }
            ]
          },
          'plugins': ['dnd', 'contextmenu']
        }).on('create_node', function(e, data) {
          // 获取父节点的所有属性
          var parentNode = data.parent;
          var parentAttrs = $('#jstree').jstree('get_node', parentNode);
          
          // 复制父节点的属性到新节点
          var newNode = $('#jstree').jstree('get_node', data.node);
          newNode.icon = parentAttrs.icon;
          newNode.li_attr = parentAttrs.li_attr;
          newNode.a_attr = parentAttrs.a_attr;
          newNode.state = parentAttrs.state;
          
          // 更新节点文本为父节点文本+子节点序号(可自定义)
          var childCount = $('#jstree').jstree('get_children_dom', parentNode).length;
          newNode.text = parentAttrs.text + ' - 子节点' + childCount;
          
          // 刷新节点应用修改
          $('#jstree').jstree('refresh_node', parentNode);
        });
      });
    "))
  ),
  jstreeOutput("jstree")
)

server <- function(input, output, session) {
  output$jstree <- renderJstree({
    jstree()
  })
}

shinyApp(ui, server)

关键代码解释

  1. 获取父节点属性:在create_node事件回调中,通过$('#jstree').jstree('get_node', parentNode)获取父节点的完整属性集合,包括图标、样式、状态等。
  2. 复制属性到新节点:将父节点的icon、li_attr、a_attr、state直接赋值给新生成的子节点,确保样式继承。
  3. 自定义子节点文本:根据父节点下的子节点数量生成有序的子节点文本,替换原代码中无意义的序号+字母组合。
  4. 刷新节点:调用refresh_node方法让修改后的属性立即生效。

内容的提问来源于stack exchange,提问作者Shakeel Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:45:34