对于冗长的代码示例,我深表歉意,但我不得不从 shinydashboard 主页复制一个带有 tabItems 的示例。
您的方法几乎没有问题。首先,如果您检查menuItems,您会看到实际选项卡的ID 不是tabItem2,而是shiny-tab-tabItem2。这一点,加上a 标签内的额外属性data-toggle="tab" 足以打开所需的选项卡。片段:
a("Computation Completed", href="#shiny-tab-tabItem2", "data-toggle" = "tab")
但是,这有其局限性。首先也是最明显的,侧边栏中menuItem 的状态未设置为active。这看起来很奇怪,人们可能不相信,一个已被移动到另一个选项卡。
其次,不太明显,如果您(在服务器端)监听选项卡更改,您将不会获得有关此选项卡切换的信息。这些是由单击menuItem 触发的,并且选项卡本身不会报告它是否可见或隐藏。
所以,我的做法是模拟点击对应的menuItem,这样就解决了以上所有问题。
代码示例:
library(shiny)
library(shinydashboard)
ui <- shinyUI(
dashboardPage(
dashboardHeader(title = "Some Header"),
dashboardSidebar(
sidebarMenu(
menuItem("Computations", tabName = "tabItem1", icon = icon("dashboard")),
menuItem("Results", tabName = "tabItem2", icon = icon("th"))
)
),
dashboardBody(
tags$script(HTML("
var openTab = function(tabName){
$('a', $('.sidebar')).each(function() {
if(this.getAttribute('data-value') == tabName) {
this.click()
};
});
}
")),
tabItems(
tabItem(tabName = "tabItem1",
fluidRow(
box(plotOutput("plot1", height = 250)),
box(
title = "Controls",
sliderInput("slider", "Number of observations:", 1, 100, 50)
)
),
infoBoxOutput("out1")
),
tabItem(tabName = "tabItem2",
h2("Widgets tab content")
)
)
)
)
)
server <- function(input, output){
histdata <- rnorm(500)
output$plot1 <- renderPlot({
data <- histdata[seq_len(input$slider)]
hist(data)
})
output$out1 <- renderInfoBox({
infoBox("Completed",
a("Computation Completed", onclick = "openTab('tabItem2')", href="#"),
icon = icon("thumbs-o-up"), color = "green"
)
})
}
shinyApp(ui, server)
注意,唯一重要的是onclick 属性,而不是href。这意味着,每个div 或其他元素都可用于创建此链接。您甚至可以使用此onclick 命令获得竖起大拇指的图像。
如果您还有其他问题,请发表评论。
最好的问候
编辑:整个信息框均可点击。
这是对 OmaymaS 评论的回答。关键是让 infoBox 成为可点击的容器。为了实现这一点,可以定义一个新函数来制作一个稍微不同的 infoBox。自定义框如下:
customInfoBox <- function (title, tab = NULL, value = NULL, subtitle = NULL, icon = shiny::icon("bar-chart"), color = "aqua", width = 4, href = NULL, fill = FALSE) {
validateColor(color)
tagAssert(icon, type = "i")
colorClass <- paste0("bg-", color)
boxContent <- div(class = "info-box", class = if (fill) colorClass,
onclick = if(!is.null(tab)) paste0("$('.sidebar a')).filter(function() { return ($(this).attr('data-value') == ", tab, ")}).click()"),
span(class = "info-box-icon", class = if (!fill) colorClass, icon),
div(class = "info-box-content",
span(class = "info-box-text", title),
if (!is.null(value)) span(class = "info-box-number", value),
if (!is.null(subtitle)) p(subtitle)
)
)
if (!is.null(href)) boxContent <- a(href = href, boxContent)
div(class = if (!is.null(width)) paste0("col-sm-", width), boxContent)
}
此代码是从原始infoBox 函数定义复制而来的,只有带有onclick 的行是新的。我还在容器内添加了openTab 函数(带有一些抽搐),这样您就不必担心将该函数放在视图中的什么位置。我觉得可能有点超负荷。
此自定义信息框可以与默认信息框完全一样使用,如果您传递额外的tab 参数,则会添加到侧边栏的链接。
编辑:字幕利用
正如 Alex Dometrius 提到的,使用 subtitle 会导致此功能崩溃。这是因为意外插入的脚本标记被用作subtitle 参数,以便与框一起呈现。为了腾出这个位置,我在顶部编辑了主要示例,使脚本标签位于 dashboardBody 的顶层(实际上在 ui 中的任何位置都可以)。
(为避免混淆:在版本 1 中,tags$script 是在 infobox 内部提供的,它被解释为 subtitle 参数。)