r Shiny中的简单模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r Shiny中的简单模块相关的知识,希望对你有一定的参考价值。

# UI ==========================================================================

confirmModalInput = function(id) {
  ns <- NS(id)
  
  tagList(
    actionButton(ns("show"), "Show modal dialog"),
    verbatimTextOutput(ns("print"))
  )
}


# Server ======================================================================

confirmModalServer = function(input, output, session) {
  ns <- session$ns
  
  # Create object to store reactive values
  vals <- reactiveValues(
    txt = NULL,
    error_msg = NULL,
    print = FALSE
  )
  
  # Create modal
  popupModal <- function() {
    modalDialog(
      textInput(ns("txt"), "Write something"),
      
      textOutput(ns("skip_error_msg")),
      
      footer = tagList(
        modalButton("Cancel"),
        actionButton(ns("ok"), "OK")
      )
    )
  }
  
  # Show modal when button is clicked
  observeEvent(input$show, {
    vals$error_msg <- NULL
    showModal(popupModal())
  })
  
  # Validate submission
  observeEvent(input$ok, {
    vals$txt <- input$txt
    
    if (!is.null(vals$txt) && nzchar(vals$txt)) {
      removeModal()
      vals$print <- TRUE
    } else {
      vals$error_msg <- "You did not input anything."
    }
  })
  
  # Output error message
  output$skip_error_msg <- renderText({
    vals$error_msg
  })
  
  # Output inputted text
  output$print <- renderPrint({
    if (vals$print) {
      vals$txt
    } else {
      NULL
    }
  })
}
# UI ==========================================================================

textModalInput = function(id) {
  ns <- NS(id)
  
  tagList(
    textInput(ns("txt"), "Write something")
  )
}

# Server ======================================================================

textModalServer = function(input, output, session) {
  mytext <- reactive({
    input$txt
  })
  return(mytext)
}
library(shiny)
source("modules/module_1.R")
source("modules/module_2.R")

ui = basicPage(
  # module 1
  strong("Module 1", style = "color:steelblue;"),
  textModalInput("txt_modal"),
  textOutput("txt"),
  
  # module 2
  strong("Module 2", style = "color:steelblue;"),
  br(),
  confirmModalInput("confirm_modal")
)

server = function(input, output, session) {
  # module 1
  confirm_txt <- callModule(textModalServer, "txt_modal")
  
  output$txt <- renderText({
    confirm_txt()
  })
  
  # module 2
  callModule(confirmModalServer, "confirm_modal")
}

shinyApp(ui, server)

以上是关于r Shiny中的简单模块的主要内容,如果未能解决你的问题,请参考以下文章

R Shiny,调用模块中的 DT::replaceData 不起作用

r 将模块中返回的值存储在Shiny中的reactiveValues中

r 在Shiny模块中返回reactiveValues

将函数连接到 R Shiny Dashboard 中的 actionButton

R Shiny 启用/禁用 UI 模块

R Shiny 模块不会在同一事件中响应式更新