You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny应用中实现按钮显示?附现有代码片段

Complete Shiny App to Reveal Hidden Elements on Button Click

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 renderPrint blocks 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:43