我想创建一个模块化的闪亮应用程序,它最初会显示文本,但在单击 actionButton() 后隐藏它。现在文本始终保留。我的代码:
(应用程序。R)
library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(dplyr)
# Load the modules
source("sideUI.R")
source("sideServer.R")
source("textUI.R")
source("textServer.R")
# Build UI & server and then run the app
ui <- dashboardPage(
dashboardHeader(title = "Text Hiding Example"),
dashboardSidebar(sideUI("side")), # Sidebar with the action button
dashboardBody(
useShinyjs(), # Initialize shinyjs
textUI("textPL") # Text UI module
)
)
server <- function(input, output, session) {
# Use the reactive in another module
btn_input <- sideServer("side")
textServer("textPL", btn = btn_input$btn)
}
shinyApp(ui, server)
textUI.R
textUI <- function(id) {
ns <- NS(id)
tagList(
div(
id = ns("showtext"),
p("This text will be hidden after clicking the button", style = "font-size: 16px; text-align: center;")
)
)
}
文本服务器.R
textServer <- function(id, btn) {
moduleServer(
id,
function(input, output, session) {
ns <- session$ns # Namespace function
# Observe button click event
observeEvent(btn(), {
shinyjs::hide(ns("showtext")) # Hide the text with correct namespace
})
}
)
}
sideUI.R
sideUI <- function(id) {
ns <- NS(id)
tagList(
actionButton(ns("action"), "Hide Text")
)
}
sideServer.R
sideServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
return(btn = reactive(input$action)) # Return the button input as reactive
}
)
}
app.R
中,您应该仅将 btn_input
而不是 btn_input$btn
传递给 textServer()
函数。具体:
server <- function(input, output, session) {
# Use the reactive in another module
btn_input <- sideServer("side")
textServer("textPL", btn = btn_input)
}
textServer.R
中,不应将 "showtext"
包裹在 ns()
中。具体:
observeEvent(btn(), {
shinyjs::hide("showtext")
})