想實(shí)現(xiàn)在頁面1上點(diǎn)擊按鈕店溢,跳轉(zhuǎn)到頁面2呼股,每個(gè)頁面作為一個(gè)module蜜暑。
錯(cuò)誤的寫法:
模塊之間的變量不共享,無法達(dá)到預(yù)期目的绽族。
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.")
)}
當(dāng)然我這個(gè)navbarPage直接點(diǎn)擊上面導(dǎo)航欄就可以跳轉(zhuǎn)姨涡,做按鈕是多余的衩藤,只是為了示例吧慢。