2

当使用闪亮的模块和 DT::datatable 我想访问 selected_rows 服务器端。如果我的 DT:datatable ID 是,my_DT_table那么我希望该对象input$my_DT_table_selected_rows包含所选行的索引。这在没有模块的闪亮应用程序中非常有效。

但是,如果我使用模块,那么这种方法不再有效,输入对象input$my_DT_table_selected_rows不再包含所选行的索引。

4

1 回答 1

2

使用 DT:datatable 函数时,我们可以使用内置功能来了解 UI 中的选定行。

对象:input$my_DT_table_rows_selected包含所选行的索引,其中my_DT_table是 DT::datatable 的 ID。

但是,在使用模块时,表的名称现在不同了。它的前缀等于用于调用模块 UI 功能的 ID。因此,如果该 ID 是,my_ID那么表名将变为:(my_ID-table_name注意 ID 后面的连字符)。这可以使用浏览器中的开发工具(例如 FireFox 中的检查器)轻松验证。然后关联的输入对象名称变为(我们需要反引号以防止 R 将连字符解释为减号):

input$`my_ID-table_name_rows_selected`

这是一个非常基本的示例,其中包含一些关于如何将反应对象传递给模块的额外学习。反应对象包含所选行的索引。我需要在没有括号的情况下通过它。在 module_server 函数内部,我用括号指代反应性对象。

ui_module.R 中的UI 模块

module_ui <- function(id) {
  ns <- NS(id) # create namespace

  tagList(
    fluidRow(column(6, DT::dataTableOutput(ns("dt_table")))),
    fluidRow(column(4, verbatimTextOutput(ns("render_selected_line"))))
  )
}

server_module.R 中的服务器模块

table_server <- function(input, output, session, data) {

  output$dt_table <- DT::renderDataTable(
    DT::datatable(
    data = data,
    selection = "single"
    )
  )
}

selected_line_server <- function(input, output, session, data) { 
  output$render_selected_line <- renderText({
    paste0("My selection was: ", data()) # refer to the reactive object with parenthesis
  })

}

闪亮的应用

library(shiny)
library(dplyr)
library(DT)

source("./modules/ui_module.R")
source("./modules/server_module.R")

ui <- fluidPage(
  module_ui("my_ID")
)

server = function(input, output, session) {
  data <- mtcars
  callModule(table_server, id = "my_ID", data = data) # data is not reactive
  callModule(selected_line_server, id = "my_ID", data = selectedLine) # refer to the reactive object selectedLine without parenthesis

  selectedLine <- reactive({
    req(input$`my_ID-dt_table_rows_selected`)
    if (is.null(input$`my_ID-dt_table_rows_selected`)) {
      return(NULL)
    } else {
      rows_selected <- as.numeric(input$`my_ID-dt_table_rows_selected`) # we need to prefix dt_table_rows_selected with the ID of the UI function "my_ID" and a hyphen
    }
  })

}

shinyApp(ui = ui, server = server)
于 2020-01-21T06:36:15.497 回答