如何在R Shiny中点击动作按钮后渲染R代码编写的HTML内容?
解决方案
要实现点击按钮后渲染指定HTML内容,你可以通过以下方式简化操作,无需使用繁琐的paste()拼接:
关键修复点
- 用
tagList()包裹多元素:在renderUI中返回多个UI元素时,必须用tagList()组合,否则Shiny只会渲染第一个元素。 - 修正CSS语法:原代码中
font-size = 25px写法错误,应改为font-size: 25px(CSS属性使用冒号而非等号)。 - 绑定按钮触发逻辑:调用
randomVals()让renderUI依赖于按钮点击事件,确保只有点击"Go"后才更新内容。
修正后的完整代码
ui <- fluidPage( h4(strong("Project Description")), p(style="text-align: justify; font-size: 25px", "Shiny-Box is a Shiny application made with the purpose of", em("demonstrating various use of shiny features"), "that are frequently asked by users but rarely discussed in a beginner or formal class environment. With an example app and its code, Shiny-Box hopefully will ease your understanding on the mechanism of various Shiny features. Go to", a(href = "https://github.com/NabiilahArdini/Shiny-Box", "Shiny-Box GitHub Page"), "to find more details on the source code."), tags$blockquote("Shiny-Box is still under continuous development. Please look forward to future updates!"), hr(), actionButton("go", "Go"), numericInput("n", "n", 50), uiOutput("text") ) server <- function(input, output) { randomVals <- eventReactive(input$go, { runif(input$n) }) output$text <- renderUI({ # 触发依赖,确保仅在点击按钮后更新 temp <- randomVals() # 使用tagList包裹所有需要渲染的元素 tagList( h4(strong("Project Description")), p(style="text-align: justify; font-size: 25px", "Shiny-Box is a Shiny application made with the purpose of", em("demonstrating various use of shiny features"), "that are frequently asked by users but rarely discussed in a beginner or formal class environment. With an example app and its code, Shiny-Box hopefully will ease your understanding on the mechanism of various Shiny features. Go to", a(href = "https://github.com/NabiilahArdini/Shiny-Box", "Shiny-Box GitHub Page"), "to find more details on the source code."), tags$blockquote("Shiny-Box is still under continuous development. Please look forward to future updates!"), hr() ) }) } shinyApp(ui, server)
额外优化建议
如果这段内容是固定的,可提前定义为独立UI组件,让代码更整洁:
# 提前定义固定内容组件 project_desc <- tagList( h4(strong("Project Description")), p(style="text-align: justify; font-size: 25px", "Shiny-Box is a Shiny application made with the purpose of", em("demonstrating various use of shiny features"), "that are frequently asked by users but rarely discussed in a beginner or formal class environment. With an example app and its code, Shiny-Box hopefully will ease your understanding on the mechanism of various Shiny features. Go to", a(href = "https://github.com/NabiilahArdini/Shiny-Box", "Shiny-Box GitHub Page"), "to find more details on the source code."), tags$blockquote("Shiny-Box is still under continuous development. Please look forward to future updates!"), hr() ) # server中直接返回组件 output$text <- renderUI({ randomVals() project_desc })
内容的提问来源于stack exchange,提问作者Nova
相关产品推荐
相关产品推荐

