我当前的应用程序有一个使用 uiOutput
和 renderUI
动态呈现的 actionButton
,这样它的标签就会根据用户的操作而变化。这是一个非常愚蠢的表示:
library(shiny)
# Define UI
ui <- fluidPage(
#Have a button to press
actionButton("test_button",
uiOutput("button_label"),
icon = icon("forward"))
)
# Define server
server <- function(input, output) {
#Have a reactive value serving as a switch
reactives1 <- reactiveValues(label_switch = 0)
#Increment the switch upon every button press
observeEvent(input$test_button, {
reactives1$label_switch = reactives1$label_switch + 1
})
#Depending on whether the switch is odd or event, dynamically render the button label.
observeEvent(reactives1$label_switch, {
if(reactives1$label_switch %% 2 == 0) {
output$button_label <- renderUI({ "I'm happy!" })
} else {
output$button_label <- renderUI({ "I'm sad!" })
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
但令人沮丧的是,我似乎不知道如何使用按钮上的图标执行完全相同的操作。例如,这不起作用:
library(shiny)
# Define UI
ui <- fluidPage(
#Have a button to press
actionButton("test_button",
"Press this button to change the icon!",
uiOutput("button_icon"))
)
# Define server
server <- function(input, output) {
#Have a reactive value serving as a switch
reactives1 <- reactiveValues(icon_switch = 0)
#Increment the switch upon every button press
observeEvent(input$test_button, {
reactives1$icon_switch = reactives1$icon_switch + 1
})
#Depending on whether the switch is odd or event, dynamically render the button icon.
observeEvent(reactives1$icon_switch, {
if(reactives1$icon_switch %% 2 == 0) {
output$button_icon <- renderUI({ shiny::icon("arrow-left") })
} else {
output$button_icon <- renderUI({ shiny::icon("arrow-right") })
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
R Shiny 似乎没有意识到 icon()
正在被调用;我收到一个错误,我需要使用 shiny::icon()
来呈现图标,即使这就是我正在做的事情。我见过here我可能需要动态渲染整个按钮,但除非必须,否则我宁愿不这样做。它也没有解释为什么我可以使用按钮标签而不是按钮图标来实现这个技巧。我在其他地方看到 renderUI()
调用可能会覆盖我的图标对象的类/形式,但我在哪里调用 icon()
似乎并不重要>;无论哪种方式我都会收到错误。
我错过了什么?
最佳答案
借助 fontawesome 包,您可以在标签中包含图标。
不要在观察者内部使用render
函数,不建议这样做。
library(shiny)
library(fontawesome)
# Define UI
ui <- fluidPage(
#Have a button to press
actionButton("test_button",
uiOutput("button", inline = TRUE))
)
# Define server
server <- function(input, output) {
#Have a reactive value serving as a switch
reactives1 <- reactiveValues(icon_switch = 0)
#Increment the switch upon every button press
observeEvent(input$test_button, {
reactives1$icon_switch = reactives1$icon_switch + 1
})
#Depending on whether the switch is odd or event, dynamically render the button icon.
output$button <- renderUI({
if(reactives1$icon_switch %% 2 == 0) {
tags$span("Press the button", fa_i("arrow-left"))
} else {
tags$span("Press the button", fa_i("arrow-right"))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
关于r - 如何在 R 中动态渲染按钮图标 Shiny ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73208737/