gpt4 book ai didi

r - 观察Shiny中的模式(轻松)关闭

转载 作者:行者123 更新时间:2023-12-04 02:16:36 28 4
gpt4 key购买 nike

我正在寻找一种在easy-close选项为TRUE时基于Shiny模态关闭触发事件的方法(因此,在模态外部单击将其关闭)。由于没有链接到模式的ID,因此我似乎无法捕获此事件。我尝试在“观察”事件中包装模态,但这只会触发模态的打开,而不会触发模态的关闭。

有任何想法吗...
谢谢



示例:如果要通过在事件模式外部单击来关闭该模式,则要触发事件,而不是单击关闭按钮。下面的代码仅在打开时触发...

library(shiny)
ui <- fluidPage(
fluidRow(
actionButton(inputId = "enterText", label = "Enter name", align = "left"),
h1(textOutput("myOutput"))
)
)

server <- function(input, output, session) {
myText <- reactiveValues(input = "...")
myModal = modalDialog(h3("Enter a string, then click outside this modal to close and display the text"),
textInput(inputId = "myString", label = "Enter a string: "),
title = "Input", easyClose = TRUE, footer = modalButton("Dismiss"))
test = observe(myModal)

#Open the modal when button clicked
observeEvent(input$enterText,{
showModal(myModal)
})

#Observe the modal, should fire when it CLOSES by clicking outside the modal (easy-close)
observeEvent(test, {
myText$input = input$myString
print("observed")
}, ignoreInit = T)

output$myOutput = renderText(myText$input)

}

shinyApp(ui = ui, server = server)

最佳答案

我想为不要求使用easyClose = TRUE的任何人提供一个更简单的答案,就像OP那样-在这种情况下,这比SBista注释中的链接要容易得多。

这只是用您自己的操作按钮替换了模态的默认“关闭”按钮,这使您可以在关闭模态时执行一些其他操作。这是通过footer =参数设置的。

在此示例中,模态包含复选框,直到关闭模态后复选框才生效。

library(shiny)
shinyApp(
ui <- fluidPage(
fluidRow(
## Button to display modal:
actionButton(inputId = "display_modal",label = "Display modal"),
## Print the choices that were made in the modal:
h1(textOutput("checked_letters"))
)
),

server <- function(input, output) {
## These values allow the actions made in the modal to be delayed until the
# modal is closed
values = reactiveValues(to_print = "", ## This is the text that will be displayed
modal_closed=F) ## This prevents the values$to_print output from
# updating until the modal is closed

## Open the modal when button clicked
observeEvent(input$display_modal,{
values$modal_closed <- F
showModal(modalDialog(
checkboxGroupInput("checkboxes",label = "Select letters",
choices = LETTERS[1:7]),
## This footer replaces the default "Dismiss" button,
# which is 'footer = modalButton("Dismiss")'
footer = actionButton("dismiss_modal",label = "Dismiss")
))
})

## This event is triggered by the actionButton inside the modalDialog
# It closes the modal, and by setting values$modal_closed <- T, it
# triggers values$to_print to update.
observeEvent(input$dismiss_modal,{
values$modal_closed <- T
removeModal()
})
## values$to_print is only updated once the modal is closed.
observe({
if(values$modal_closed){
values$to_print <- paste(input$checkboxes)
}
})
## Forward the values$to_print to the UI
output$checked_letters = renderText({values$to_print})
}
)

关于r - 观察Shiny中的模式(轻松)关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45245681/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com