我的目标是构建菜单,其中内容是动态生成的,用户只能看到从顶部到所选内容的menuItems / menuSubItems(" next"按钮将用于到达下一个尚未显示的menuItems / menuSubItems;如果选择任何可用的menuItems / menuSubItems菜单,则应重新生成菜单,以便选择最后一个可用的menuItems / menuSubItems)。因此,我必须使用选定的和 startExpanded 参数,但这不是此问题的一部分。
我遇到的问题是renderMenu
和observeEvent
的相互连接(检查选定的menuItem / menuSubItem)。这是代码:
library(shiny)
library(shinydashboard)
menu_generator <- function(selected = NULL, expanded = NULL){
print("menu_generator")
output <- sidebarMenu(
menuItem("Charts1", icon = icon("bar-chart-o"),
menuSubItem("AAdashboard", tabName = "AAdashboard"),
menuSubItem("BBdashboard", tabName = "BBdashboard")
),
menuItem("Charts2", icon = icon("bar-chart-o"),
menuSubItem("DDdashboard", tabName = "DDdashboard"),
menuSubItem("EWidgets", tabName = "EWidgets")
)
)
return(output)
}
ui <- dashboardPage(
dashboardHeader(title = "Test"),
dashboardSidebar(sidebarMenu(
sidebarMenuOutput("menu_output")
)),
dashboardBody(
tabItems(
tabItem(tabName = "AAdashboard",
h2("ADashboard tab content")
),
tabItem(tabName = "BBdashboard",
h2("BWidgets tab content")
),
tabItem(tabName = "DDdashboard",
h2("DWidgets tab content")
),
tabItem(tabName = "EWidgets",
h2("EWidgets tab content")
)
))
)
server <- function(input, output) {
output$menu_output <- renderMenu({
print("output$menu_output")
sidebarMenu(menu_generator(),
id = "my_menu")
})
observeEvent(input$my_menu, {
print("observer")
print(input$my_menu)
print(input$sidebarItemExpanded)
output$menu_output <- renderMenu({
sidebarMenu(menu_generator(),
id = "my_menu")
})
})
}
shinyApp(ui, server)
场景:展开Charts2,然后点击&#34; DDdashboard&#34;。
在控制台中:
[1] "observer"
[1] "DDdashboard"
[1] "Charts2"
[1] "menu_generator"
[1] "observer"
[1] "AAdashboard"
NULL
[1] "menu_generator"
&#34;观察者&#34;被调用两次(因此&#34; menu_generator&#34;也),因此这会产生意外行为。我的理解是,原因是renderMenu
的性质。问题是 - 如何防止Shiny呼叫&#34;观察者&#34;在这种情况下两次?另请注意,在第二个电话input$my_menu
=&#34; AAdashboard&#34;。
答案 0 :(得分:-1)
observeEvent(input$sidebarItemExpanded == 'DDdashboard',{
print("DDdashboard_selected")
})