R闪亮-重置renderText

时间:2020-01-08 18:12:37

标签: r shiny shinyjs

在以下代码中,目标是在单击button1之后基于所选值重置文本输出的值:

library(shiny)
library(shinythemes)
library(DT, warn.conflicts = FALSE) #shiny also uses: dataTableOutput & renderDataTable
library(shinyjs)
library(shinyBS) #for tooltips on an input or output.
library(htmltools)

ui <- fluidPage(theme = shinytheme("lumen"),

                useShinyjs(),

                titlePanel(""),

                selectInput(
                  inputId = "test1",
                  label = strong("pick something"),
                  choices = c("a - button shows", "b - button hidden", "c - button hidden"),
                  selected = "b",
                  selectize = TRUE,
                  width = "175px",
                  multiple = FALSE),

                hidden(actionButton("button1", "Click Me")),

                htmlOutput(outputId = "textoutput")
)

server <- function(input, output, session) {

  output$textoutput <- renderText({

    if (input$test1 == "a - button shows"){
      print("a")
      shinyjs::show("button1")
      paste("<i><span style='color:blue'>You chose a. You should click the button.</span></i>")
    }

    else if (input$test1 == "b - button hidden"){
      print("b")
      shinyjs::hide("button1")
      paste("<i><span style='color:green'>You chose b. No button.</span></i>")
    }

    else {
      shinyjs::hide("button1")
      print("c")
      paste("<i><span style='color:orange'>The button is hidden.</span></i>")
    }

  })

  observeEvent(input$button1,{
    print(input$test1)
    output$textoutput <- renderText({ paste("<i><span style='color:purple'>You clicked the button.</span></i>")})
    shinyjs::hide("button1")
  })

}

# Create Shiny object
shinyApp(ui = ui, server = server)

按原样运行代码,然后单击按钮,文本变为You clicked the button.。我遇到的问题是,当下拉菜单的值更改为“ b”或“ c”(单击按钮后)时,文本不会更改。我知道为什么它没有改变,但是还没有提出解决方案。

1 个答案:

答案 0 :(得分:0)

我想您希望一个output$textoutput可以根据输入中的各种变化进行更新。

也许reactive值可能包含您希望呈现的消息。例如:

server <- function(input, output, session) {

  msg_txt <- reactiveVal("")

  observe({
    if (input$test1 == "a - button shows"){
      print("a")
      shinyjs::show("button1")
      msg_txt("<i><span style='color:blue'>You chose a. You should click the button.</span></i>")
    }

    else if (input$test1 == "b - button hidden"){
      print("b")
      shinyjs::hide("button1")
      msg_txt("<i><span style='color:green'>You chose b. No button.</span></i>")
    }

    else {
      shinyjs::hide("button1")
      print("c")
      msg_txt("<i><span style='color:orange'>The button is hidden.</span></i>")
    }

  })

  output$textoutput <- renderText({ msg_txt() })

  observeEvent(input$button1,{
    print(input$test1)
    msg_txt("<i><span style='color:purple'>You clicked the button.</span></i>")
    shinyjs::hide("button1")
  })

}

这是否具有您想要的行为?