gpt4 book ai didi

R Shiny : How to hide tabPanel by a condition in server

转载 作者:行者123 更新时间:2023-12-01 19:31:43 25 4
gpt4 key购买 nike

我修改了 here 中给出的答案使用 Shiny 编写一个非常简单的登录/注销系统如果 USER$Logged 为 FALSE(即用户已注销),我想隐藏面板“B”,并在 USER$Logged 为 TRUE(即用户已登录)时显示它。换句话说,一旦运行代码,它不应该显示面板 B,直到用户正确输入用户名和密码。我尝试使用条件面板,但它不会隐藏面板 B。当前无论 USER$Logged 如何,它都始终显示它。有谁知道如何解决吗?

library(shiny)
library(shinydashboard)
my_username <- "test"
my_password <- "abc"
shinyApp(
shinyUI(
navbarPage( tabPanel("A", uiOutput('loginpage')),
tabPanel("B", uiOutput('page1'),conditionalPanel(condition = "output.cond1==TRUE"))
)
),
shinyServer(function(input, output, session) {
USER <<- reactiveValues(Logged = FALSE)
observe({
if (USER$Logged == FALSE) {
output$loginpage <- renderUI({
box(title = "",textInput("userName", "Username"),
passwordInput("passwd", "Password"),
br(),
actionButton("Login", "Log in"))})
} else if (USER$Logged == TRUE) {
output$loginpage <- renderUI({fluidPage(
box(title = "",br(),br(),actionButton("logout", "Logout"))
)

})
}
})

observeEvent(input$Login, {
if (!is.null(input$Login)) {
if (input$Login > 0) {
Username <- isolate(input$userName)
Password <- isolate(input$passwd)
Id.username <- which(my_username == Username)
Id.password <- which(my_password == Password)
if (length(Id.username) > 0 & length(Id.password) > 0) {
if (Id.username == Id.password) {
USER$Logged <<- TRUE

}
}
}
}

})

observeEvent(input$logout, {
USER$Logged <<- FALSE
})

output$cond1 = reactive({
USER$Logged==TRUE
})

} ))

最佳答案

您可以使用shinyjs包以显示/隐藏选项卡。为此,我添加了 idnavbar这样我们就可以选择要显示/隐藏的选项卡。您可以添加 shinyjs::show/hide在你的observe当用户登录或注销时显示或隐藏选项卡。最后一点是您需要调用 useShinyjs()在你的用户界面的某个地方,这样功能就可以工作了。我还对您的代码进行了一些小的编辑(例如,删除 <<- 。该应用程序是:

library(shinyjs)
shinyApp(
shinyUI(
navbarPage( id = "navbar",
useShinyjs(),
tabPanel("A", uiOutput('loginpage')),
tabPanel("B", uiOutput('page1'),conditionalPanel(condition = "output.cond1==TRUE"))
)
),
shinyServer(function(input, output, session) {
USER <- reactiveValues(Logged = FALSE)

observe({
if (USER$Logged == FALSE) {
output$loginpage <- renderUI({
box(title = "",textInput("userName", "Username"),
passwordInput("passwd", "Password"),
br(),
actionButton("Login", "Log in"))})

shinyjs::hide(selector = "#navbar li a[data-value=B]")

} else if (USER$Logged == TRUE) {
output$loginpage <- renderUI({fluidPage(
box(title = "",br(),br(),actionButton("logout", "Logout"))
)})

shinyjs::show(selector = "#navbar li a[data-value=B]")
}

})

observeEvent(input$Login, {
Id.username <- which(my_username == input$userName)
Id.password <- which(my_password == input$passwd)
if(Id.username & Id.password) USER$Logged <<- TRUE
})

observeEvent(input$logout, {
USER$Logged <- FALSE
})
}))

关于R Shiny : How to hide tabPanel by a condition in server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50062820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com