为什么 toggleState 不适用于 R Shiny 中的 modalDialog?

Why toggleState does not work with modalDialog in R Shiny?

当我使用 shinyjs::togglestate 将来自 UI 的所有输入变量与 modalDialog 的输入变量进行比较时,它仅在第一次起作用。如果我关闭模态对话框并再次打开它,它不起作用!

反应规则是:

if they are equal: button is blocked
if they are different: the button is enabled

Obs:模态对话框变量的值必须是 UI 中选择的输入值。 (这是一个非常常见的例子,如果你有一个数据库检查并且你只是想更新它,如果有什么改变)

我创建了这个简单的应用程序来解决这个问题。 只是 运行 它,单击按钮一次,观察预期的行为,关闭模态对话框,单击第二次并观察它不再起作用,但是如果您更改模态对话框中的某些值,然后返回到原始状态输入值突然 "remembers" 再次工作。

library(shiny)
library(shinyjs)

shinyApp(
  ui =
    fluidPage(
      useShinyjs(),
      sidebarLayout(
        sidebarPanel(
                     textInput("txt1","text"),
                     selectInput("select1","select",c("A","B","C")),
                     numericInput("n1","numeric",1),
                     dateInput("d1","date",value = Sys.Date()),

                     actionButton("go", "Go")),
      mainPanel())
    ),

  server =
    function(input, output, session) {


      observe({
        shinyjs::toggleState("click", !(input$txt1    == input$txt2 &&
                                        input$select1 == input$select2 &&
                                        input$n1      == input$n2 &&
                                        input$d1      == input$d2  
                                        ) )
        })

observeEvent(input$go,{
  showModal(
    modalDialog(
      textInput("txt2", "text", input$txt1),
      selectInput("select2", "select", c("A","B","C"), input$select1),
      numericInput("n2", "numeric", input$n1 ),
      dateInput("d2", "date", value = input$d1),

      actionButton("click", "Click")
    )
  )

})


    }
)

为什么会出现这种意外行为?有什么解决方法吗?

提前致谢!

您的代码中的问题是 observe 仅在创建输入时计算,然后在输入更改时计算。每次单击 go 时,您都需要评估切换条件。因此,除了使用 observe 之外,您还需要使用 observeEvent。修改后的服务器代码如下所示:

server =
function(input, output, session) {

  observe({
    shinyjs::toggleState("click", !(input$txt1    == input$txt2 &&
                                      input$select1 == input$select2 &&
                                      input$n1      == input$n2 &&
                                      input$d1      == input$d2
    ) )
  })

  observeEvent(input$go,{
    showModal(
      modalDialog(
        textInput("txt2", "text", input$txt1),
        selectInput("select2", "select", c("A","B","C"), input$select1),
        numericInput("n2", "numeric", input$n1 ),
        dateInput("d2", "date", value = input$d1),

        actionButton("click", "Click")
      )
    )

  })

  observeEvent(input$go,{
    shinyjs::toggleState("click", !(input$txt1    == input$txt2 &&
                                      input$select1 == input$select2 &&
                                      input$n1      == input$n2 &&
                                      input$d1      == input$d2
    ) )
  })


}

希望对您有所帮助!