我在输出中没有看到
dynamicUIModule
中的文本。我的模块化 Shiny 应用程序出了什么问题?
library(shiny)
dynamicUIModule <- function(input, output, session) {
output$dynamic_ui <- renderUI({
h3("This is a test!")
})
}
# Main UI
ui <- fluidPage(
numericInput("num_input", "Enter a number:", value = 1),
uiOutput("dynamic_ui"), # This will display content from serverOnlyModule
textOutput("display_num")
)
# Main Server
server <- function(input, output, session) {
# Calling the server-only module
callModule(dynamicUIModule, "dynamic1")
# Other server logic
output$display_num <- renderText({
paste0("Squared value: ", input$num_input^2)
})
}
# Run the application
shinyApp(ui = ui, server = server)
我发现问题了。我也应该添加 UI 模块。例如:
library(shiny)
sidebarUI <- function(id) {
ns <- NS(id)
tagList(
uiOutput(ns("dynamic_ui"))
)
}
dynamicUIModule <- function(input, output, session, squaredValue) {
output$dynamic_ui <- renderUI({
if (squaredValue() > 10) {
sliderInput(session$ns("dynamic_slider"), "Value is large! Adjust:", min = 1, max = 100, value = 50)
} else {
h3("Value is small!")
}
})
}
library(shiny)
# Source the module
# Main UI
ui <- fluidPage(
numericInput("num_input", "Enter a number:", value = 1),
sidebarUI("dynamic1"), # This ID should match the ID in renderUI of the module
textOutput("display_num")
)
# Main Server
server <- function(input, output, session) {
squaredValue <- reactive({
input$num_input^2
})
# Calling the dynamic UI module
callModule(dynamicUIModule, "dynamic1", squaredValue = squaredValue)
# Using the squared value in the main server logic
output$display_num <- renderText({
paste0("Squared value: ", squaredValue())
})
}
# Run the application
shinyApp(ui = ui, server = server)