r - 隐藏和清除 selectInput
问题描述
我需要显示\隐藏输入,如果输入不存在,我会得到 NULL 或空字符串,这里是可重现的例子:
ui <-
dashboardPage(
dashboardHeader(
title = 'Test'),
dashboardSidebar(),
dashboardBody(
selectInput(
inputId = 'mainInput',
label = 'Main input',
selected = 'Show',
choices = c('Show', 'Hide')
),
uiOutput(
outputId = 'secondInputUI'
),
actionButton(
inputId = 'thirdInput',
label = 'Check value'
)
)
)
server <- function(input, output, session){
observeEvent(input$mainInput, ignoreNULL = TRUE, {
if (input$mainInput == 'Show')
output$secondInputUI <-
renderUI(
selectInput(
inputId = 'secondInput',
label = 'Second input',
selected = 0,
multiple = FALSE,
choices = c(1, 0)
)
)
else {
output$secondInputUI <-
renderUI(
selectInput(
inputId = 'secondInput',
label = 'Second input',
selected = '',
multiple = TRUE,
choices = c(1, 0)
)
)
# If uncommit - input value don't update and will return latest available before delete input
# output$secondInputUI <-
# NULL
}
})
observeEvent(input$thirdInput, {
showNotification(
session = session,
ui = paste(input$secondInput, collapse = ', '))
})
}
shinyApp(
ui = ui,
server = server)
您可以看到将 NULL 设置为 uioutput 的注释部分,如果它处于活动状态 - 在清除该 ui 之前闪亮返回最新的可用值,那么如何处理呢?
解决方案
我觉得我懂了。您可以创建一个独立于 UI 的反应变量,因为当 UI 元素被移除时输入不会更新。
library(shiny)
library(shinydashboard)
ui <-
dashboardPage(
dashboardHeader(
title = 'Test'),
dashboardSidebar(),
dashboardBody(
selectInput(
inputId = 'mainInput',
label = 'Main input',
selected = 'Show',
choices = c('Show', 'Hide')
),
uiOutput(
outputId = 'secondInputUI'
),
actionButton(
inputId = 'thirdInput',
label = 'Check value'
)
)
)
server <- function(input, output, session){
secondInputVar <- reactive({
if(input$mainInput == 'Show'){
input$secondInput
} else {
}
})
observeEvent(input$mainInput, ignoreNULL = TRUE, {
if (input$mainInput == 'Show')
output$secondInputUI <-
renderUI(
selectInput(
inputId = 'secondInput',
label = 'Second input',
selected = 0,
multiple = FALSE,
choices = c(1, 0)
)
)
else {
output$secondInputUI <- renderUI({
NULL
})
}
})
observeEvent(input$thirdInput, {
showNotification(
session = session,
ui = paste(secondInputVar(), collapse = ', '))
})
}
shinyApp(
ui = ui,
server = server)
推荐阅读
- php - 在队列中运行导入作业并让用户知道导入何时完成
- c++ - OpenGL GLFW,三角形不渲染
- xml - 将 XML 文件转换为 CSV
- resources - 如何处理 Hugo 目录结构之外的大量资源文件
- azure-devops - 通过访问令牌使用 Azure DevOps 的 REST API 获取用户详细信息
- profiling - Valgrind 报告 RocksDB 中的内存泄漏
- caching - Magnolia“页面感知”缓存
- arrays - 如何使用 swift 将新数据传输到数组?
- corda - 在corda帐户中找不到匿名方(DLC2iDbLTxfABXk2UgFJzej8RbX6hUQuCjYBDJATYjYAJW)错误
- php - 我的捆绑包没有自动注册