首页 > 解决方案 > 如何使用按钮更改 R 闪亮应用程序中的页面

问题描述

我正在尝试使用按钮来更改闪亮应用程序中的页面。我发现了像这样的例子,这些例子看起来很简单,但由于某种原因,我无法让它发挥作用。下面是我在app.R文件中创建的可重现示例。这将创建一个双页应用程序,在第一页上有一个按钮,但单击该按钮不会将您移动到第二页。任何提示将非常感谢。

pageButtonUi <- function(id) {
  actionButton(NS(id, "page_change"),
               label="Change the Page")
}


pageButtonServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
    observeEvent(input$page_change, {
      updateNavbarPage(session=session,
                       inputId="pages",
                       selected="second_page")
    })
  })
}


ui <- navbarPage(
  title="test",
  id="pages",
  tabPanel(title="first page",
           sidebarLayout(
             sidebarPanel(
               pageButtonUi("page")
             ),
             mainPanel(
             )
           )
  ),
  tabPanel(title="second_page", "second_page")
)


server <- function(input, output, session) {
  pageButtonServer("page")
}


shinyApp(ui, server)

标签: rshiny

解决方案


您正在使用闪亮的模块。tabPanel 是在顶级 UI 中定义的,但您正在尝试使用较低级别(模块)服务器来更新顶级 UI。这行不通。因此,您需要使用顶级服务器来更新顶级 UI。换句话说,您需要将父session对象传递给您的模块。

这是解决方法:

library(shiny)


pageButtonUi <- function(id) {
    actionButton(NS(id, "page_change"),
                 label="Change the Page")
}


pageButtonServer <- function(id, parentSession) {
    moduleServer(id, function(input, output, session) {
        
        observeEvent(input$page_change, {
            updateNavbarPage(session=parentSession,
                             inputId="pages",
                             selected="second_page")
        })
    })
}


ui <- navbarPage(
    title="test",
    id="pages",
    tabPanel(title="first page",
             sidebarLayout(
                 sidebarPanel(
                     pageButtonUi("page")
                 ),
                 mainPanel(
                 )
             )
    ),
    tabPanel(title="second_page", "second_page")
)


server <- function(input, output, session) {
    pageButtonServer("page", parentSession = session)
}


shinyApp(ui, server)

即使对于高级用户来说,这也不容易理解。尝试阅读 Rstudio 文章,看看他们如何定义session会有帮助。


推荐阅读