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

Shiny新手技术咨询:点击按钮后隐藏文本输入框与按钮并仅在点击后显示文本输出

Solution for Your Shiny App Requirements

Hey there! Since you're already using shinyjs, we can leverage it to easily implement your desired behavior. Here's the simplified, fixed code with clear explanations:

Updated Code

ui.R

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  textInput("caption", "Caption", "abc"),
  actionButton("btn_input", "Enter"),
  verbatimTextOutput("value")
)

server.R

library(shiny)
library(shinyjs)

server <- function(input, output) {
  # Initialize a reactive value to hold our output text, starts empty
  output_text <- reactiveVal(NULL)
  
  # Trigger action only when the button is clicked
  observeEvent(input$btn_input, {
    # Get the input value without triggering unnecessary reactivity
    v <- isolate(input$caption)
    
    # Generate the desired output string based on input
    result <- if (v == "xxx") paste(v, "a") else paste(v, "b")
    
    # Update our reactive value with the processed result
    output_text(result)
    
    # Hide the input box (including its "Caption" label) and button
    hide("caption")
    hide("btn_input")
  })
  
  # Render output only after we have a valid result (post-button click)
  output$value <- renderPrint({
    req(output_text())  # Skip rendering until output_text has a value
    output_text()
  })
}

Key Changes Explained

  • reactiveVal for Output Control: We use output_text <- reactiveVal(NULL) to store our processed result. Initially it's NULL, so the output area stays empty at startup.
  • observeEvent for Button Triggers: This block only runs when the "Enter" button is clicked. Inside it, we:
    • Isolate the input value to avoid unintended reactivity loops
    • Generate the result string per your logic
    • Update the reactive value to trigger output rendering
    • Use shinyjs::hide() to make the input box and button disappear
  • req() in Output Render: The req(output_text()) ensures the output only shows up once we have a valid result (after the button is clicked), so nothing displays initially.

This approach keeps things simple, uses the libraries you're already working with, and perfectly matches your requirements!

内容的提问来源于stack exchange,提问作者LJG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:32:50