You need to enable JavaScript to run this app. 模块化R Shiny应用:updateTabItem后updatePickerInput不生效
优惠活动
大模型
产品
解决方案
定价
更多

模块化R Shiny应用:updateTabItem后updatePickerInput不生效

模块化R Shiny应用开发问题

实现目标

  • 点击选中DT表格的某一行后,自动切换到对应标签页
  • 同步将目标页的pickerInput值更新为选中行的对应内容

现存问题

  • 已参考其他帖子的方案,通过传入父session实现了标签页正常切换,但updatePickerInput始终无法生效
  • 初步判断问题出在session和inputId参数的传值逻辑上:按照模块化运行规则,updatePickerInput需要传入跳转目标picker模块对应的子session,而非当前table模块的session或全局父session,目前传值不匹配导致功能失效

运行环境(sessionInfo)

  • R版本:4.0.3 (2020-10-10)
  • 平台:x86_64-apple-darwin17.0 (64-bit)
  • 运行系统:macOS Big Sur 10.16

可复现示例

以下为单文件app.R脚本,两个功能模块均定义为全局函数:

# Dependencies ----
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(dplyr)
library(DT)

# Picker Module ----
# Picker UI
picker_ui <- function(id){
    box(width = 12
        , uiOutput(NS(id, "picker"))
    )
}
# Picker Server
picker_server <- function(id){
    moduleServer(id, function(input, output, session){
        # render pickerInput
        output$picker <- renderUI({
            ls_choices <- c("One", "Two", "Three")
            pickerInput(NS(id, "pickerInput")
                        , choices = ls_choices
                        , selected = NULL)
        })
    })
}

# Table Module ----
# Table UI
table_ui <- function(id){
    fluidPage(
        box(width  = 12
            , DTOutput(NS(id, "table"))
        )
    )
}
# Table Server
table_server <- function(id, parent){
    moduleServer(id, function(input, output, session){
        output$table <- renderDT({
            data <- c("One", "Two", "Three")
            df <- tibble("Labels" = data)
            datatable(df, rownames = F, selection = "single", options = list(dom = 'tip'))
        })
        observeEvent(input$table_cell_clicked, {
            req(input$table_cell_clicked$value)
            updateTabItems(session = parent, inputId = "tabs", selected = "picker")
            ################
            #### ISSUE #####
            ################
            updatePickerInput(session = session, inputId = "pickerInput", selected =  input$table_cell_clicked$value)
        })
    }) 
}

# Shiny App----
# UI
ui <- dashboardPage(
    dashboardHeader(title = "Demo")
    , dashboardSidebar(
        sidebarMenu(
            id = "tabs"
            , menuItem("Table", tabName = "table")
            , menuItem("Picker Input", tabName = "picker")
        )
    )
    , dashboardBody(
        tabItems(
            tabItem(tabName = "table"
                    , table_ui("table")
            )
            , tabItem(tabName = "picker"
                      , picker_ui("picker")
            )
        )
    )
)

# Server
server <- function(input, output, session) {
    table_server("table", session)
    picker_server("picker")
}

# Run App ----
shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 16:06:02