【问题标题】:In R Shiny, how to eliminate the flashing of observeEvent conditionals when first invoking the App?在R Shiny中,第一次调用App时如何消除observeEvent条件的闪烁?
【发布时间】:2021-12-24 14:47:56
【问题描述】:

在下面的 MWE 代码中,用户可以通过单击输入 2 的“显示”单选按钮来选择调用对象 input2。默认设置是隐藏 input2。但是,在第一次调用应用程序时,input2 会快速闪烁,然后被observeEvent 隐藏。

这种闪烁在非 MWE 版本的代码中更为明显。

有一个相关的帖子 In R shiny, how to eliminate flashing of all conditional panels in sidebar when first invoking the App without using renderUI? 解决了 conditionalPanel 的这个问题。但是这里没有conditionalPanel

我不想用renderUI 来解决这个问题!!由于renderUI 有缺点,我不想重新介绍。

MWE 代码:

library(shiny)
library(shinyjs)

f <- function(action,i){as.character(checkboxInput(paste0(action,i),label=NULL))}
actions       <- c("show", "reset")
tbl           <- t(outer(actions, c(1,2), FUN = Vectorize(f)))
colnames(tbl) <- c("Show", "Reset")
rownames(tbl) <- c("Input 2", "Input 3")

ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$style(HTML(
      "td .checkbox {margin-top: 0; margin-bottom: 0;}
       td .form-group {margin-bottom: 0;}"
    ))
  ),
  br(),
  sidebarLayout(
    sidebarPanel(
      numericInput("input1", "Input 1:", 10, min = 1, max = 100),
      h5(strong("Add inputs:")),
      tableOutput("checkboxes"),
      numericInput("input2", "Input 2:", 10, min = 1, max = 100),
    ),
    mainPanel()
  )    
)

server <- function(input, output, session){
  
  output[["checkboxes"]] <- 
    renderTable({tbl}, 
                rownames = TRUE, align = "c",
                sanitize.text.function = function(x) x
    )

  observeEvent(input[["show1"]], {
    if(input[["show1"]] %% 2 == 1){shinyjs::show(id = "input2")} else
      {shinyjs::hide(id = "input2")}
  })

}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny shiny-reactivity shinyjs


    【解决方案1】:

    在第一次调用observerEvent 之前,在事件循环中需要一些时间。 默认情况下,它将显示在最开始。 这导致闪光。 只需将input2 隐藏在server 函数的开头即可:

    server <- function(input, output, session) {
      # Avoid flashing
      shinyjs::hide(id = "input2")
      
      output[["checkboxes"]] <-
        renderTable(
          {
            tbl
          },
          rownames = TRUE,
          align = "c",
          sanitize.text.function = function(x) x
        )
    
      observeEvent(input[["show1"]], {
        if (input[["show1"]] %% 2 == 1) {
          shinyjs::show(id = "input2")
        } else {
          shinyjs::hide(id = "input2")
        }
      })
    }
    

    【讨论】:

      【解决方案2】:

      你也可以使用hidden

      hidden(numericInput("input2", "Input 2:", 10, min = 1, max = 100))
      

      toggle:

        observeEvent(input[["show1"]], {
          toggle("input2")
        },ignoreNULL = FALSE)
      

      【讨论】:

        猜你喜欢
        • 2021-09-12
        • 2019-08-01
        • 1970-01-01
        • 2021-08-26
        • 2021-11-08
        • 1970-01-01
        • 2013-06-04
        • 2021-12-21
        • 2017-11-06
        相关资源
        最近更新 更多