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

Shiny反应式表格中prettySwitch显示为复选框问题求助

解决Shiny DT表格中prettySwitch显示为复选框的问题

问题根源是shinyWidgets组件所需的CSS/JS资源未被正确加载,导致prettySwitch无法渲染成开关样式,回退为原生复选框。以下是具体修复方案:

修复步骤

  1. 在UI中显式调用useShinyWidgets(),确保加载组件所需的样式和脚本
  2. 优化响应式数据处理逻辑,避免使用全局赋值<<-(提升代码规范性)

修改后的完整代码

library(shiny)
library(shinyWidgets)
library(DT)

Labels <- c(
  "Invalid Speciation",
  "Invalid Fraction",
  "Invalid Unit"
)

Explanations <- c(
  "The speciation provided for a given characteristic is not valid. Would you like to remove invalid speciation data?",
  "Remote invalid fraction data?",
  "Remove data width invalid units for a given characteristic and media combination?"
)

shinyApp(
  ui = fluidPage(
    useShinyWidgets(), # 新增:加载shinyWidgets资源
    DT::dataTableOutput('x1'),
    verbatimTextOutput('x2')
  ),
  
  
  server = function(input, output, session) {
    
    # 创建输入组件的函数
    newInput <- function(len, id, value, ...){
      if (length(value) == 1) value <- rep(value, len)
      inputs = character(len)
      for (i in seq_len(len)) {
        inputs[i] = as.character(prettySwitch(paste0(id, i), label = NULL, value = value[i], status = "primary", fill = TRUE))
      }
      inputs
    }
    
    # 获取输入值的函数
    shinyValue <- function(id, len) {
      unlist(lapply(seq_len(len), function(i) {
        value = input[[paste0(id, i)]]
        if (is.null(value)) TRUE else value
      }))
    }
    
    n = length(Labels)
    # 用reactiveVal存储表格数据,替代全局变量
    df_data <- reactiveVal(
      data.frame(
        Label = Labels,
        Explanation = Explanations,
        Remove = newInput(n, 'switch_', TRUE),
        stringsAsFactors = FALSE
      )
    )
    
    loopData = reactive({
      current_values <- shinyValue('switch_', n)
      # 更新reactiveVal中的数据,避免全局赋值
      df <- df_data()
      df$Remove <- newInput(n, 'switch_', current_values)
      df_data(df)
      df
    })
    
    
    output$x1 = DT::renderDataTable(
      isolate(loopData()),
      escape = FALSE, selection = 'none', rownames=FALSE,
      options = list(
        dom = 't', paging = FALSE, ordering = FALSE,
        preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
        drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
      ))
    
    output$x2 = renderPrint({
      data.frame(Selected = Labels[shinyValue('switch_', n)])
    })
  }
)

关键说明

  • useShinyWidgets()会自动加载shinyWidgets组件依赖的CSS和JavaScript,确保prettySwitch能渲染出预期的开关样式
  • 使用reactiveVal管理表格数据,避免全局变量带来的潜在问题,让响应式逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:25:07