R Shiny 中 rhandsontable 内部模态的 ID

ID for rhandsontable inside modal in R Shiny

我的目标是通过单击操作按钮在模式中显示(有条件的)editable rhandsontable。创建和显示 table 工作正常,但是我正在努力研究如何在 ui 中为 table 正确分配 ID 以识别用户更改。

感谢任何帮助,谢谢:)

library(shiny)

ui <- fluidPage(
  actionButton('openModal', "Open Modal")
  # rHandsontableOutput("DataEditor") # doesn't work
)

server <- function(input, output, session) {
  
  observeEvent(input$openModal, {
    irrelevant_condition <- FALSE # include that rhandsontable doesn't have to appear always
    if (irrelevant_condition == TRUE) {
      return(showModal(modalDialog("Choose some variables to display first")))
    } else {
      # display rhandsontable if user made a valid choice
      showModal(modalDialog(  
        updDataEditor()
      ))
    }
  })
  
  updDataEditor <- function() {
    output$DataEditor <- renderRHandsontable({
      # in real app some conditional calculations leading to a DF called 'current.DF'
      # why function?: in real app with variation, depending on some inputs the user chose
      current.DF <- data.frame(Name = c("Name1", "Name2"), value1 = c(0,0), value2=c(0,0)) # example df
      rhandsontable(current.DF) 
    })
  }
    
  observeEvent(input$DataEditor, {
    # Here's the problem
    # won't get called when DataEditor is modified by the user
    browser() 
    return()
  })
  
}
shinyApp(ui,server)

这是这样工作的:

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  actionButton('openModal', "Open Modal")
)

server <- function(input, output, session) {
  
  current.DF <- reactive(
    data.frame(Name = c("Name1", "Name2"), value1 = c(0,0), value2=c(0,0))
  )
  
  observeEvent(input$openModal, {
    irrelevant_condition <- FALSE # include that rhandsontable doesn't have to appear always
    if (irrelevant_condition == TRUE) {
      return(showModal(modalDialog("Choose some variables to display first")))
    } else {
      # display rhandsontable if user made a valid choice
      showModal(modalDialog(  
        rHandsontableOutput("DataEditor")
      ))
    }
  })
  
  output$DataEditor <- renderRHandsontable({
    rhandsontable(current.DF()) 
  })
  
  observeEvent(input$DataEditor, {
    print(input$DataEditor$changes)
  })
  
}
shinyApp(ui,server)

是你想要的吗?对于可以更改的数据框,我会使用反应值。如果只有一些单元格被更改,你可以使用 set_data 函数,更好。


编辑解决评论中提出的问题:

  output$DataEditor <- renderRHandsontable({
    rhandsontable(current.DF()) %>% htmlwidgets::onRender(
      "function(el){var hot = this.hot; setTimeout(function(){hot.render();}, 1000)}"
    )
  })