【问题标题】:how to use a button to change pages in an R shiny app如何使用按钮更改 R 闪亮应用程序中的页面
【发布时间】:2021-11-05 03:55:51
【问题描述】:

我正在尝试使用按钮来更改闪亮应用中的页面。我发现像this one 这样的例子看起来很简单,但由于某种原因我无法让它工作。下面是我在 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)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您正在使用闪亮的模块。 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 会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 2021-02-26
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多