想实现在页面1上点击按钮,跳转到页面2,每个页面作为一个module。
错误的写法:
模块之间的变量不共享,无法达到预期目的。
app.R
library(shiny)
source("page1.R")
source("page2.R")
ui <- navbarPage(
title = "test",
id = "test",
ui.page1(0),
ui.page2(0)
)
server <- function(input, output, session) {
s1 <- server.page1(0)
}
shinyApp(ui = ui, server = server)
page1.R
ui.page1 <- function(id) {
ns <- NS(id)
tabPanel(
title = "page1",
value ="page1",
actionButton(inputId = ns("jt2"),label = "Jump to page 2")
)}
server.page1 <- function(id) {
moduleServer(id,function(input, output, session) {
observeEvent(input$jt2, {
updateNavbarPage(session, inputId = "test", selected = "page2")
}
)
}
)
}
page2.R
ui.page2 <- function(id) {
ns <- NS(id)
tabPanel(
title = "page2",
value = "page2",
tags$h1("Here is page 2.")
)}
正确写法
app.R
library(shiny)
source("page1.R")
source("page2.R")
ui <- navbarPage(
title = "test",
id = "test",
ui.page1(0),
ui.page2(0)
)
server <- function(input, output, session) {
s1 <- server.page1(0)
observeEvent(s1$jt2(), {
updateNavbarPage(session, inputId = "test", selected = "page2")
})
}
shinyApp(ui = ui, server = server)
page1.R
ui.page1 <- function(id) {
ns <- NS(id)
tabPanel(
title = "page1",
value = "page1",
actionButton(inputId = ns("jt2"),label = "Jump to page 2")
)}
server.page1 <- function(id) {
moduleServer(id,module = function(input, output, session) {
return(list(jt2 = reactive({input$jt2})))
}
)
}
page2
ui.page2 <- function(id) {
ns <- NS(id)
tabPanel(
title = "page2",
value = "page2",
tags$h1("Here is page 2.")
)}
当然我这个navbarPage直接点击上面导航栏就可以跳转,做按钮是多余的,只是为了示例。