shinyWidgets包awesomeRadio组件能否设置初始无选中选项?
问题说明
开发R Shiny应用时,参照Shiny原生radioButtons()输入组件的用法,给shinyWidgets包的awesomeRadio()组件传入selected = character(0)参数,想要实现组件初始加载时无任何选项被选中的效果,但实测该参数不被awesomeRadio()支持,无法达成预期。
最小可复现示例
if (interactive()) { library(shiny) library(shinyWidgets) ui <- fluidPage( br(), awesomeRadio(inputId = "id1", label = "Make a choice:", #selected = character(0), choices = c("graphics", "ggplot2")), radioButtons(inputId = "id2", label = "Make a choice:", selected = character(0), choices = c("graphics", "ggplot2")), verbatimTextOutput(outputId = "res1"), verbatimTextOutput(outputId = "res2") ) server <- function(input, output, session) { output$res1 <- renderPrint(input$id1) output$res2 <- renderPrint(input$id2) } shinyApp(ui = ui, server = server) }
解决方法
awesomeRadio()内部自带参数校验逻辑:如果UI端传入的selected参数长度为0,会自动替换为第一个选项值,因此直接在UI端传selected = character(0)会被组件逻辑覆盖,无法生效。
要实现初始无选中的效果,需要在Server端借助updateAwesomeRadio()函数,在应用会话启动后主动清空组件选中值,修改后的可运行代码如下:
if (interactive()) { library(shiny) library(shinyWidgets) ui <- fluidPage( br(), awesomeRadio( inputId = "id1", label = "Make a choice:", choices = c("graphics", "ggplot2"), selected = "graphics" # UI端先传入任意一个选项作为初始值,避免触发组件内部校验报错 ), radioButtons( inputId = "id2", label = "Make a choice:", selected = character(0), choices = c("graphics", "ggplot2") ), verbatimTextOutput(outputId = "res1"), verbatimTextOutput(outputId = "res2") ) server <- function(input, output, session) { # 会话启动后立刻清空awesomeRadio的选中状态 updateAwesomeRadio( session = session, inputId = "id1", selected = character(0) ) output$res1 <- renderPrint(input$id1) output$res2 <- renderPrint(input$id2) } shinyApp(ui = ui, server = server) }
实现效果和原生
radioButtons()传selected = character(0)完全一致:初始加载时无选项被选中,组件初始返回值为NULL,用户点击选项后才会返回对应选项值。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

