我不熟悉执行您所描述的操作的简单方法,但这当然并不意味着没有;)这里有一个小解决方法,我相信它符合您的要求,并使您的代码相对干净。我们可以用reactiveValuesToList(input)
获取我们的输入列表,然后编写一个禁用或启用所有输入的函数。我们也可以决定只切换button
通过根据属性对列表进行子集化来输入。
下面是工作示例,希望对您有所帮助!
library(shiny)
library(shinyjs)
ui <- fluidPage(
h3('Disable all inputs while running'),
actionButton('btn_all_inputs','Run long process'),
h3('Disable only buttons while running'),
actionButton('btn_only_buttons','Run long process'),
hr(),
h3('Inputs'),
textInput('text1', 'Text1',"my text:"),
actionButton('btn1','Button 1'),
actionButton('btn2','Button 2'),
actionButton('btn3','Button 3'),
sliderInput('slid3','Slider 1',min=0,max=1,value=0.5),
useShinyjs()
)
server <- function(input, output, session){
# Function to toggle input elements.
# input_list: List of inputs, reactiveValuesToList(input)
# enable_inputs: Enable or disable inputs?
# Only buttons: Toggle all inputs, or only buttons?
toggle_inputs <- function(input_list,enable_inputs=T,only_buttons=FALSE)
{
# Subset if only_buttons is TRUE.
if(only_buttons){
buttons <- which(sapply(input_list,function(x) {any(grepl('Button',attr(x,"class")))}))
input_list = input_list[buttons]
}
# Toggle elements
for(x in names(input_list))
if(enable_inputs){
shinyjs::enable(x)} else {
shinyjs::disable(x) }
}
observeEvent(input$btn_all_inputs,{
input_list <- reactiveValuesToList(input)
toggle_inputs(input_list,F,F)
Sys.sleep(5)
toggle_inputs(input_list,T,F)
})
observeEvent(input$btn_only_buttons,{
input_list <- reactiveValuesToList(input)
toggle_inputs(input_list,F,T)
Sys.sleep(5)
toggle_inputs(input_list,T,T)
})
}
shinyApp(ui = ui, server = server)
替代解决方案
该解决方案使用自定义JavaScript
根据 Shiny 忙还是闲来启用/禁用所有输入。因此,这将在 Shiny 繁忙时禁用您的输入。我现在将脚本设置为禁用所有按钮,但您可以通过添加更多选择来轻松扩展它document.getElementsByTagName()
。希望这更接近您的想法。
library(shiny)
ui <- fluidPage(
h3('Disable buttons while running'),
actionButton('btn_run','Run long process'),
hr(),
h3('Inputs'),
textInput('text1', 'Text1',"my text:"),
actionButton('btn1','Button 1'),
sliderInput('slid3','Slider 1',min=0,max=1,value=0.5),
includeScript('script.js')
)
server <- function(input, output, session){
observeEvent(input$btn_run,{
Sys.sleep(5)
})
}
shinyApp(ui = ui, server = server)
脚本.js
$(document).on("shiny:busy", function() {
var inputs = document.getElementsByTagName("button");
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
});
$(document).on("shiny:idle", function() {
var inputs = document.getElementsByTagName("button");
console.log(inputs);
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
});