如何在R Shiny中实现checkboxGroupButton样式的单选按钮
解决方案
方法1:直接使用radioGroupButtons()(推荐)
shinyWidgets包内置的radioGroupButtons()函数,样式和checkboxGroupButtons()完全一致,且原生支持单选逻辑,无需额外处理,是最直接的解决方案。
修改后的完整代码:
library(shiny) library(shinyWidgets) ui <- fluidPage( tags$h1("单选按钮(与checkboxGroupButtons样式一致)"), radioGroupButtons( inputId = "somevalue1", label = "Make a choice: ", choices = c("A", "B", "C") ), verbatimTextOutput("value1") ) server <- function(input, output) { output$value1 <- renderPrint({ input$somevalue1 }) } if (interactive()) shinyApp(ui, server)
方法2:通过JavaScript强制checkboxGroupButtons()实现单选
如果必须基于checkboxGroupButtons()改造,可以添加一段JavaScript代码,实现点击某一选项时自动取消其他选项的选中状态:
library(shiny) library(shinyWidgets) ui <- fluidPage( tags$h1("checkboxGroupButtons改为单选"), checkboxGroupButtons( inputId = "somevalue1", label = "Make a choice: ", choices = c("A", "B", "C") ), verbatimTextOutput("value1"), # 注入JS逻辑 tags$script(HTML(" $('#somevalue1 .btn').on('click', function() { // 移除其他按钮的active样式 $('#somevalue1 .btn').not(this).removeClass('active'); // 取消其他按钮对应的input勾选状态 $('#somevalue1 .btn').not(this).find('input').prop('checked', false); }); ")) ) server <- function(input, output) { output$value1 <- renderPrint({ input$somevalue1 }) } if (interactive()) shinyApp(ui, server)
说明:方法1是官方推荐的实现方式,样式和交互逻辑更稳定;方法2适合需要基于现有checkboxGroupButtons做定制化修改的场景。
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

