如何获取 Flexdashboard 文档中的当前活动选项卡以反应显示不同 UI

How to get the current active tab in a Flexdashboard document to reactively display different UI

我目前正在尝试制作一个 Flexdashboard 闪亮的应用程序。鉴于哪个选项卡在我的输出区域中处于活动状态,我希望能够在侧边栏中显示不同的 UI。

为此,我考虑使用 renderUI 和一些基本条件。但我的问题是我不知道如何在 flexdashboard 中获取活动选项卡。我做了一些研究,但找不到相关信息。我不确定我们是否可以像 shiny 那样将 id 添加到 tabset 中,如果可能的话,如何获得与 id 对应的结果。

这是我想做的一些框架代码:

---
title: "Test"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
---
```{r setup, include=FALSE}
suppressPackageStartupMessages({
library(shiny)
library(flexdashboard)
})
```


# Page 1

## Input {.sidebar}

```{r}
radioButtons("radio", label = h3("Radio buttons"),
  choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3), 
  selected = 1)


output$list1 <- renderUI({
  if (tab == "Tabs 1") {
    selectInput("select", label = h3("Select box"), 
      choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3), 
      selected = 1)
  } 
  else {}
})

uiOutput("list1")
```

Column {.tabset }
-------------------------------------

### Tab 1

### Tab 2

### Tab 3

感谢您的帮助:)

似乎与 tabsetPanel(..., id = "xyz") 中创建了 input$xyz 变量的情况不同,Rmarkdown 并没有表现出同样的礼貌。

因此,我们需要借助一些 JavaScript:

自己破解该功能
---
title: "Test"
runtime: shiny
output:
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
---
<script>
$("body").on("shown.bs.tab", "a[data-toggle='tab']", function(e) {
   Shiny.setInputValue("active_tab", $(e.target).parent().index());
})
</script>

我们告诉 shiny 每当显示一个选项卡时,我们要将输入变量(即我们可以在 shiny 侧做出反应的东西)设置为相应的选项卡编号 (0基于)。

然后我们可以使用input$active_tab来设置我们的服务器逻辑:

output$list1 <- renderUI({
   sel <- input$active_tab
   if (is.null(sel) || sel == 0) {
      selectInput("select", label = h3("Select box"),
                  choices = list("Choice A1", "Choice A2", "Choice A3"),
                  selected = 1)
   } else if (sel == 1) {
      selectInput("select", label = h3("Select box"),
                  choices = list("Choice B1", "Choice B2", "Choice B3"),
                  selected = 1)
   } else {
            selectInput("select", label = h3("Select box"),
                  choices = list("Choice C1", "Choice C2", "Choice C3"),
                  selected = 1)
   }
})

注意。 我想有一个比 shown.bs.tab 更好的事件可以附加事件处理程序。这可能有助于避免在 render 部分测试 NULL 案例。发生这种情况,因为显然 shown.bs.tab 在默认情况下显示第一个选项卡时不会触发。