闪亮 - 隐藏actionButton,当renderUI值为null时动态创建

时间:2018-02-25 21:11:52

标签: r shiny

我有下面的应用程序(简化示例)。基本上我想,当我打开应用程序时,如果反应值等于"",我不希望UI上出现activeButton。目前正在出现,但没有标签。在这种情况下我该怎么办?谢谢你的帮助!

library(shiny)
runApp(list(ui=
    shinyUI(fluidPage(

        mainPanel(
            textInput("text", label = ""),
            uiOutput("wordOneButton")
        )
    ))
,

server=shinyServer(function(session, input, output) {
    reval <- reactive(sample(c("a", "b", ""), 1))

    # Fill the buttons with the random letter
    output$wordOneButton <- renderUI({
        actionButton("action", label = reval()[1])
        })


    # Include predicted word in the text after click event on button
    observeEvent(input$action, {
        name <- paste0(input$text, reval()[1], sep = " ")
        updateTextInput(session = session, "text", value = name)
    })

})
))

2 个答案:

答案 0 :(得分:1)

您需要添加shinyjs::toggle()

library(shiny)

runApp(list(ui=
    shinyUI(fluidPage(
        shinyjs::useShinyjs(), #NEW
        mainPanel(
            textInput("text", label = ""),
            uiOutput("wordOneButton")
        )
    ))
,

server=shinyServer(function(session, input, output) {
    reval <- reactive(sample(c("a", "b", ""), 1))

    # Fill the buttons with the random letter
    output$wordOneButton <- renderUI({
        actionButton("action", label = reval()[1])
        })

    observe(shinyjs::toggle("wordOneButton", condition = reval() != "")) #NEW

    # Include predicted word in the text after click event on button
    observeEvent(input$action, {
        name <- paste0(input$text, reval()[1], sep = " ")
        updateTextInput(session = session, "text", value = name)
    })

})
))

答案 1 :(得分:1)

这绝对是可能的,无需调用其他库。您正在寻找的两个功能是validate()need()。只需添加几行代码即可确认反应式reval()与空字符串""是不同的:

library(shiny)
runApp(list(ui=
              shinyUI(fluidPage(

                mainPanel(
                  textInput("text", label = ""),
                  uiOutput("wordOneButton")
                )
              ))
            ,

            server=shinyServer(function(session, input, output) {
              reval <- reactive(sample(c("a", "b", ""), 1))

              # Fill the buttons with the random letter
              output$wordOneButton <- renderUI({

                # Validate that reval() is distinct than ""
                shiny::validate(
                  shiny::need(reval() != "", message = "")
                )

                actionButton("action", label = reval()[1])
              })


              # Include predicted word in the text after click event on button
              observeEvent(input$action, {
                name <- paste0(input$text, reval()[1], sep = " ")
                updateTextInput(session = session, "text", value = name)
              })

            })
))

我正在使用shiny::调用来显式使用shiny库中的这些函数,并避免出现错误,以防您使用诸如jsonlite之类的其他共享相同功能的库。如果您不使用此库,请随时删除shiny::调用。

此外,如果reval()等于空字符串"",则可以添加一条消息。只需在message函数中更改need()参数即可。