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

如何在R Shiny中实现单选按钮控制文本输入显隐及默认空值保留

解决方案

以下是满足需求的完整代码:

library(shiny)

# 定义空值替换运算符,处理初始状态的空输入
`%||%` <- function(a, b) if (is.null(a)) b else a

ui <- fluidPage(
  numericInput("n", "Number", value = 1),
  uiOutput("col")
)

server <- function(input, output, session) {
  
  col_names <- reactive(paste0("staff_attended_", seq_len(input$n)))
  
  output$col <- renderUI({
    purrr::map(
      col_names(), 
      ~ tagList(
        selectInput(
          .x,
          label = "Staff Attended",
          choices = letters,
          selected = isolate(input[[.x]]),
          multiple = TRUE
        ),
        
        radioButtons(
          paste0(.x, "_type"), 
          "Staff Attended: Shift/Call-In/Contractor?",
          choices = c("Shift", "Call-In", "Contractor"),
          selected = isolate(input[[paste0(.x, "_type")]] %||% character(0))
        ),
        
        # 动态显示Contractor名称输入框
        conditionalPanel(
          condition = paste0("input['", paste0(.x, "_type"), "'] === 'Contractor'"),
          textInput(paste0(.x, "_contractor"), label = "Name of Contractor")
        )
      )
    )
  })
}

shinyApp(ui, server)

关键改动说明

1. 实现单选按钮默认空值且切换数量后保留选中状态

在radioButtons的selected参数中,使用isolate(input[[paste0(.x, "_type")]] %||% character(0)):

  • %||%运算符判断输入值是否存在:首次加载或新增控件时,用character(0)设置默认无选中状态;
  • isolate包裹输入值,避免动态UI重绘时触发不必要响应,确保切换Number值后已选中状态不丢失。

2. 选中Contractor时显示对应文本输入框

在每个动态控件组中添加conditionalPanel:

  • 条件表达式采用字符串形式,精准匹配动态生成的单选按钮ID;
  • 当单选按钮选中"Contractor"时自动显示文本输入框,选中其他选项时隐藏。

内容的提问来源于stack exchange,提问作者its.me.adam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:35:34