为什么toggleState在R Shiny中不能与modalDialog一起使用?

时间:2019-02-02 12:58:32

标签: r shiny modal-dialog shinyjs

当我使用Shinyjs :: togglestate将UI中的所有输入变量与modalDialog的输入变量进行比较时,它只能第一次使用。如果我关闭模式对话框并再次打开它,它将无法正常工作!

反应规则是:

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

Obs:模态对话框变量中的值必须是用户界面中选择的输入值。 (这是一个非常常见的示例,如果您有数据库检查,并且只想更新它(如果发生了更改))

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

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")
    )
  )

})


    }
)

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

提前谢谢!

1 个答案:

答案 0 :(得分:0)

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

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
    ) )
  })


}

希望有帮助!