我正在创建我的应用程序,我想隐藏特定的menuItem,它包含取决于用户凭据.我想为管理员/测试人员展示一切,但不是所有用户.我在堆栈溢出中发现了问题,在闪亮的dashbaord中隐藏了一个元素(框/标签),我修改了如下代码
library(shiny)
library(shinydashboard)
library(shinyjs)
ui <- dashboardPage(
dashboardHeader(title = "Set")
,dashboardSidebar(
sidebarSearchForm(label = "Search...", "searchText", "searchButton"),
sidebarMenu(
menuItem("Port", tabName = "P", icon = icon("cog"))
,menuItem("Rank", tabName = "Rank", icon = icon("cog"))
,menuItem("Mark", tabName = "Mark", icon = icon("bar-chart"))
,menuItem("Read", tabName = "Read", icon = icon("file-pdf-o"))
,useShinyjs()
,menuItem("Port, tabName = "Ocean", icon = icon("heart"))
)
,uiOutput('Super')
,uiOutput('AList')
,uiOutput('BList')
,uiOutput('DList')
,uiOutput('SList')
)
,dashboardBody(
....
)
)
server <- shinyServer(function(input, output, session) {
observeEvent(session$user,{
if (session$user == "tester") return(NULL)
hide(id = "Port", anim = TRUE)
})
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
但是,它没有用,有什么提示吗?
所以,你的方法有一个问题:menuItems
最终文档中的样子.
您提供的代码是:隐藏ID为"Port"的元素!这一切menuItems
都没问题,如果实际上有一个Id,但是当你看它们时(右击+检查),你会发现情况并非如此.
仔细检查显示,您menuItems
可以通过标签名称(= a
)和data-value
(与指定的相应的tabName
)标识在文档中.这是隐藏命令的选择参数.我不知道Shinyjs是否提供其他属性的搜索,但你也可以自己编写JS代码.
在下面的代码中,我用一个伪造了用户登录textInput
.menuItem
如果在文本字段中插入"tester",则可以观察到第一个仅显示.
完成方式:您向客户端发送消息以显示/隐藏某个项目tabName
.JS脚本在所有a
标签中搜索
存储在其data-value
属性中的给定名称的标签.隐藏是由display: none
.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Set"),
dashboardSidebar(
sidebarSearchForm(label = "Search...", "searchText", "searchButton"),
tags$head(tags$script(HTML("
Shiny.addCustomMessageHandler('manipulateMenuItem', function(message){
var aNodeList = document.getElementsByTagName('a');
for (var i = 0; i < aNodeList.length; i++) {
if(aNodeList[i].getAttribute('data-value') == message.tabName) {
if(message.action == 'hide'){
aNodeList[i].setAttribute('style', 'display: none;');
} else {
aNodeList[i].setAttribute('style', 'display: block;');
};
};
}
});
"))),
sidebarMenu(
menuItem("Port", tabName = "P", icon = icon("cog")),
menuItem("Rank", tabName = "Rank", icon = icon("cog")),
menuItem("Mark", tabName = "Mark", icon = icon("bar-chart")),
menuItem("Read", tabName = "Read", icon = icon("file-pdf-o")),
menuItem("Port", tabName = "Ocean", icon = icon("heart"))
),
uiOutput('Super'),
uiOutput('AList'),
uiOutput('BList'),
uiOutput('DList'),
uiOutput('SList')
),
dashboardBody(
textInput("user", "User ID fake.")
)
)
server <- function(input, output, session) {
observeEvent(input$user,{
if(input$user != "tester"){
session$sendCustomMessage(type = "manipulateMenuItem", message = list(action = "hide", tabName = "P"))
}else{
session$sendCustomMessage(type = "manipulateMenuItem", message = list(action = "show", tabName = "P"))
}
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)