我完全困惑为什么有两行工作代码(单独),将各自的单选按钮
重置为空(selected = character(0)
) 仅在放在 1 个“观察者”内时重置
第一行
这是最小的例子:
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
tags$script("
Shiny.addCustomMessageHandler('resetValue', function(variableName) {
Shiny.onInputChange(variableName, null);
});
"),
radioButtons("radio","Click Me",choices = c("Choice 1","Choice s"),selected = character(0)),
radioButtons("radio2","Click Me",choices = c("Choice 1","Choice s"),selected = character(0)),
actionButton("clickMe","Click Me to Reset"),
actionButton("showValue", "Show value")
)
server <- function(input, output, session) {
observeEvent(input$clickMe,{
session$sendCustomMessage(type = "resetValue", message ='radio')
updateRadioButtons(session,"radio",choices = c("Choice 1","Choice s"),selected = character(0))
session$sendCustomMessage(type = "resetValue", message ='radio2')
updateRadioButtons(session,"radio2",choices = c("Choice 1","Choice s"),selected = character(0))
})
observeEvent(input$showValue, {
print(input$radio)
print(input$radio2)
})
}
shinyApp(ui, server)
其中sendcustomMessages
用于重置
值
,这不是通过选择character(0)
来实现的>,来自即 here
最佳答案
更新
我无法弄清楚为什么无法在一个reactiveEvent中更新两个radioButton,但该错误似乎源于将selected =
参数设置为character(0)
。虽然第一个 updateRadioButtons
可与 character(0)
配合使用,但第二个则不能。
将 updateRadioButtons
的 selected =
参数中的 character(0)
更改为 0
会产生所需的结果并且以某种方式不会导致所述问题/错误。比较按钮值,最初将按钮设置为 character(0)
或 0
似乎没有区别。这两种方式的按钮值都是NULL
。使用自定义 JavaScript 函数重置值后,JS 中的值将更新为 null
。
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
tags$script("
Shiny.addCustomMessageHandler('resetValue', function(variableName) {
Shiny.onInputChange(variableName, null);
});
"),
radioButtons("radio","Click Me",choices = c("Choice 1","Choice s"),selected = character(0)),
radioButtons("radio2","Click Me",choices = c("Choice 1","Choice s"),selected = character(0)),
actionButton("clickMe","Click Me to Reset"),
actionButton("showValue", "Show value")
)
server <- function(input, output, session) {
observeEvent(input$clickMe,{
session$sendCustomMessage(type = "resetValue", message ='radio')
updateRadioButtons(session,"radio",choices = c("Choice 1","Choice s"),selected = 0)
session$sendCustomMessage(type = "resetValue", message ='radio2')
updateRadioButtons(session,"radio2",choices = c("Choice 1","Choice s"),selected = 0)
})
observeEvent(input$showValue, {
print(input$radio)
print(input$radio2)
})
}
shinyApp(ui, server)
关于r - 更新一个观察者中的多个单选按钮仅适用于第一个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242220/