r - 模块中使用的 observeEvent Shiny 函数不起作用

标签 r module shiny shiny-server

我正在开发一个应用程序,在其中我使用模块来显示不同选项卡的 ui 内容。但是,该模块似乎不与主(或父)应用程序通信。它显示正确的 ui 但无法执行 observeEvent actionButton 时的功能单击后,它应该更新当前选项卡并显示第二个选项卡。

在我的代码中,我创建了一个命名空间函数并包装了 actionButton的 ID 在 ns() ,但是它仍然不起作用。有谁知道出了什么问题?

library(shiny)

moduleUI <- function(id){

  ns <- NS(id)
      sidebarPanel(

        actionButton(ns("action1"), label = "click")
      )
}

module <- function(input, output, session){


  observeEvent(input$action1, {
    updateTabItems(session, "tabsPanel", "two")
  })
}

ui <- fluidPage(

            navlistPanel(id = "tabsPanel",

                         tabPanel("one",moduleUI("first")),
                         tabPanel("two",moduleUI("second"))
))
server <- function(input, output, session){
  callModule(module,"first")
  callModule(module,"second")

}

shinyApp(ui = ui, server = server)

最佳答案

observeEvent 有效,但由于模块只看到和知道作为输入参数提供给它们的变量,它不知道指定的 tabsetPanel,因此无法更新它。这个问题可以使用响应式值来解决,该值作为参数传递并在模块内部进行更改。更改后,主应用程序就知道它并可以更新 tabsetPanel:

library(shiny)
library(shinydashboard)

moduleUI <- function(id){

  ns <- NS(id)
  sidebarPanel(
    actionButton(ns("action1"), label = "click")
  )
}

module <- function(input, output, session, tabsPanel, openTab){

  observeEvent(input$action1, {
    if(tabsPanel() == "one"){  # input$tabsPanel == "one"
      openTab("two")
    }else{                     # input$tabsPanel == "two"
      openTab("one")
    }
  })

  return(openTab)
}

ui <- fluidPage(
  h2("Currently open Tab:"),
  verbatimTextOutput("opentab"),
  navlistPanel(id = "tabsPanel",
               tabPanel("one", moduleUI("first")),
               tabPanel("two", moduleUI("second"))
  ))


server <- function(input, output, session){
  openTab <- reactiveVal()
  observe({ openTab(input$tabsPanel) }) # always write the currently open tab into openTab()

  # print the currently open tab
  output$opentab <- renderPrint({
    openTab()
  })

  openTab <- callModule(module,"first", reactive({ input$tabsPanel }), openTab)
  openTab <- callModule(module,"second", reactive({ input$tabsPanel }), openTab)

  observeEvent(openTab(), {
    updateTabItems(session, "tabsPanel", openTab())
  })
}

shinyApp(ui = ui, server = server)

enter image description here

关于r - 模块中使用的 observeEvent Shiny 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45169876/

相关文章:

javascript - 两种代码的区别——模块

r - 更改 withProgress() 生成的消息框的样式和位置

r - 将多面 ggplots (facet_wrap) 与 R 中的牛图对齐

angular - 组件是两个模块 :AppRoutingModule and AppModule 声明的一部分

r - 直接从环境中解压 R 对象

python - 在模块之间共享资源的良好做法?

r - 在 Shiny 的fluidRow中水平居中图像

r - ShinyApps : "shinythemes" package not loading when deployed on Shinyapps. io

r - 当我使用滞后函数时,如何将前一行中的 "skip"日期与当前行中的日期相同?

r - 用另一个具有不同列名的 data.table 过滤 data.table