【问题标题】:Where are the textInput values saved from dynamic UI inputs?从动态 UI 输入中保存的 textInput 值在哪里?
【发布时间】:2020-10-31 16:45:18
【问题描述】:

我有一个应用程序,我正在根据前面的示例进行测试:How to add/remove input fields dynamically by a button in shiny

我的问题是,textInput 值保存在哪里?以及如何在mainPanel 中将它们显示为verbatimTextOutput

我尝试使用input$textin 创建renderText,但没有成功

代码如下:

library(shiny)

ui <- shinyUI(fluidPage(
  
  sidebarPanel(
    
    actionButton("add_btn", "Add Textbox"),
    actionButton("rm_btn", "Remove Textbox"),
    textOutput("counter")
    
  ),
  
  mainPanel(
    uiOutput("textbox_ui"),
  verbatimTextOutput("textout")
  )
  
))

server <- shinyServer(function(input, output, session) {
  
  # Track the number of input boxes to render
  counter <- reactiveValues(n = 0)
  
  # Track all user inputs
  AllInputs <- reactive({
    x <- reactiveValuesToList(input)
  })
  
  observeEvent(input$add_btn, {counter$n <- counter$n + 1})
  observeEvent(input$rm_btn, {
    if (counter$n > 0) counter$n <- counter$n - 1
  })
  
  output$counter <- renderPrint(print(counter$n))
  
  textboxes <- reactive({
    
    n <- counter$n
    
    if (n > 0) {
      isolate({
        lapply(seq_len(n), function(i) {
          textInput(inputId = paste0("textin", i),
                    label = paste0("Textbox", i), 
                    value = AllInputs()[[paste0("textin", i)]])
        })
      })
    }
    
  })
  
  output$textbox_ui <- renderUI({ textboxes() })
  
  output$textout <- renderText({ input$textin })
  
})

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    textInput中的Id是由inputId = paste0("textin", i)创建的,即:

    • 输入$textin1
    • 输入$textin2
    • ...

    您可以使用以下命令输出例如第一个:

    output$textout <- renderText({ input$textin1 })
    

    您也可以create a loop 输出所有新创建的输入:

      output$textout <- renderText({ 
        n <- counter$n
        paste(lapply(1:n,function(n) {input[[paste0('textin',n)]]}),collapse=' ')
        })
    

    【讨论】:

    • 这很有帮助。我如何拥有一个包含来自所有文本框的所有输入的文本输出?比如我在Textbox1中写“Hello”,然后点击Add Textbox,在Textbox2中写“World”。我希望文本输出说 Hello(下一行)World。
    • 最后一件事,如何让它们出现在新行中?
    • 折叠时可以使用 '\n' 而不是 ' '
    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2020-11-15
    • 2016-08-15
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多