【问题标题】:Unable to print updated values in Reactive inputs using Shiny无法使用 Shiny 在 Reactive 输入中打印更新的值
【发布时间】:2022-01-17 12:05:08
【问题描述】:

我们有一种情况,我们希望通过创建动态下拉列表从数据表中获取用户的输入,并希望将数据保存在本地。我们尝试了多种组合,但是这些组合在我们的场景中不起作用,例如:重置、刷新(因为我们有登录页面,所以不能使用它)。以下是可重现的例如:

代码的问题是它采用旧值而不是更新值。

library(shiny)
library(DT)

ui <- fluidPage(
  title = 'Selectinput column in a table',
  h3("Source:", tags$a("Yihui Xie", href = "https://yihui.shinyapps.io/DT-radio/")),
  numericInput('num', "enter a number", value = 5, min = 1, max = 10, step = 1),
  DT::dataTableOutput('foo'),
  verbatimTextOutput('sel'),
  actionButton(
    "saveBtn",
    "Submit Request",
    style = "color: #fff; background-color: #282364;
                                     border-color: #2e6da4",
    class = "btn btn-primary"
  )
)

server <- function(input, output, session) {
  data <- reactive({
    df <- head(iris, input$num)
    
    for (i in 1:nrow(df)) {
      df$species_selector[i] <- as.character(selectInput(paste0("sel", i),
                                                         "",
                                                         choices = unique(iris$Species),
                                                         width = "100px"))
    }
    df
  })
  
  output$foo = DT::renderDataTable(
    data(), escape = FALSE, selection = 'none', server = FALSE,
    options = list(dom = 't', paging = FALSE, ordering = FALSE),
    callback = JS("table.rows().every(function(i, tab, row) {
        var $this = $(this.node());
        $this.attr('id', this.data()[0]);
        $this.addClass('shiny-input-container');
      });
      Shiny.unbindAll(table.table().node());
      Shiny.bindAll(table.table().node());")
  )
  output$sel = renderPrint({
    str(sapply(1:nrow(data()), function(i) input[[paste0("sel", i)]]))
  })
  
  observeEvent(input$saveBtn, {
    
    Test_Data <- sapply(1:nrow(data()), function(i) input[[paste0("sel", i)]])
    Test_Data <- as.data.frame(Test_Data)
    print(Test_Data)})
  
}

shinyApp(ui, server)

一种解决方案可能是创建动态 ID,但这会在我们的模型中增加复杂性,因为我们有多个下拉菜单: https://community.rstudio.com/t/update-dt-table-dropdowns-with-reactive-data-in-shiny/96100/2

【问题讨论】:

  • 我们也一直在寻找类似的解决方案。希望高手在这里分享一下自己的看法

标签: r shiny


【解决方案1】:

您可以执行 JavaScript 以定期更新下拉菜单的选定值:

例如JavaScript 例如由函数shinyjs::runjs调用

document.getElementById("sel1").value = "versicolor"

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 2017-04-10
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多