如何在Shiny应用中实现按钮显示?附现有代码片段
First, you need to initialize shinyjs in your UI (this step was missing in your original code) using useShinyjs(). Then, in the server, we’ll set up a reactive observer to listen for clicks on the "Fetch tweets" button and reveal your hidden divs using shinyjs::show().
Here’s the full working code:
library(shiny) library(shinyjs) library(shinydashboard) UI <- fluidPage( # Initialize shinyjs (required for show/hide functionality) useShinyjs(), actionButton("get_tweets", "Fetch tweets"), numericInput("tweet_amount", "Set the amount of Tweets", 10, min = 10, max = 1000), selectInput("tweet_name", "Select the tweeter", selected = NULL, choices = c("@RealDonaldTrump")), # Hidden elements hidden(div(id="status_update", verbatimTextOutput("status"))), hidden(div(id="tweet_fetcher", verbatimTextOutput("status2"))) ) Server <- function(input, output, session) { # Trigger actions when "Fetch tweets" button is clicked observeEvent(input$get_tweets, { # Show the hidden divs shinyjs::show("status_update") shinyjs::show("tweet_fetcher") # Optional: Add sample content to the revealed outputs output$status <- renderPrint({ "Status: Fetching tweets..." }) output$status2 <- renderPrint({ paste("Successfully fetched", input$tweet_amount, "tweets from", input$tweet_name) }) }) } shinyApp(UI, Server)
Key Details:
useShinyjs(): This initializes the shinyjs library in your app—without it, the show/hide functions won’t work.observeEvent(input$get_tweets, {...}): This creates a reactive trigger that runs every time the "Fetch tweets" button is pressed.shinyjs::show("div_id"): These lines make your hidden divs visible when the button is clicked.- The
renderPrintblocks add sample text to demonstrate the revealed elements are functional. You can replace this with your actual tweet-fetching logic later.
If you want to hide the elements again (e.g., on a reset action), you can use shinyjs::hide("div_id") in another observer or button handler.
内容的提问来源于stack exchange,提问作者Henk Straten
相关产品推荐
相关产品推荐

