Shiny技术问题:如何将输入从一个模块传递到另一个模块?
在Shiny模块中获取子模块的输入值
要从子模块获取输入值,核心是让子模块的server函数返回需要传递的响应式输入对象,外部模块调用子模块时接收该对象即可访问对应值。以下是修改后的完整代码:
library(golem) library(shiny) # 1. 定义子模块 inner_module_ui <- function(id) { ns <- NS(id) fluidPage( h1("内部模块"), selectInput(inputId = ns("colName"), label = "选择列名", choices = list("A", "B", "C"), selected = "A" ), textOutput(outputId = ns("IOP")) ) } inner_module_server <- function(id) { moduleServer(id, function(input, output, session) { output$IOP <- renderPrint({ input$colName }) # 返回子模块的colName响应式对象 return(reactive(input$colName)) }) } # 2. 定义外部模块 outer_module_ui <- function(id) { ns <- NS(id) fluidPage( h1("外部模块"), inner_module_ui(ns("inner_module")), textOutput(outputId = ns("OOP")) ) } outer_module_server <- function(id) { moduleServer(id, function(input, output, session) { # 接收子模块返回的响应式对象 innerModule_colName <- inner_module_server("inner_module") output$OOP <- renderPrint({ # 调用响应式对象获取最新值 innerModule_colName() }) }) } # 3. 定义主应用 app_server <- function(input, output, session) { outer_module_server("outer_module") } app_ui <- function() { tabPanel("外部模块", outer_module_ui("outer_module")) } # 4. 运行应用 shinyApp(app_ui, app_server)
关键修改点:
- 子模块server:添加
return(reactive(input$colName)),将子模块的输入值以响应式对象的形式返回,确保外部模块能实时获取最新的输入变化。 - 外部模块server:调用子模块server时接收返回的响应式对象
innerModule_colName,在输出渲染中通过innerModule_colName()获取子模块的输入值。
内容的提问来源于stack exchange,提问作者Wang
相关产品推荐
相关产品推荐

