R 闪亮:如何构建动态 UI(文本输入) [英] R shiny: How to build dynamic UI (text input)

查看:35
本文介绍了R 闪亮:如何构建动态 UI(文本输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 R 闪亮构建动态 textInput.用户应该在文本字段中书写,然后按下添加按钮以填充另一个字段.但是,每次按下按钮时,所有字段都会变空,就像我必须提前定义我想要的字段数量一样.任何帮助将不胜感激.

I'm trying to build dynamic textInput with R shiny. The user should write in a text field then push an add button to fill another field. However, each time I push the button all the fields become empty, It's like if I must define how many fields I want in advance. Any help will be very appreciated.

谢谢

这是我的代码:

library(shiny)

shiny::runApp(list(
ui = pageWithSidebar(
headerPanel("test"),
sidebarPanel(
  helpText("Alternatives list"),
  verbatimTextOutput("summary")
),    
mainPanel(  
  actionButton("obs","add"),
  htmlOutput("selectInputs")     
)  
)
, 

server = function(input,output){
observe({

  if (input$obs == 0) 
    return()
  isolate({

    output$selectInputs <- renderUI({
      if(!is.null(input$obs))  
        print("w")
      w <- ""
      for(i in 1:input$obs) {
        w <- paste(w,textInput(paste("a",i,sep=""),paste("a",i,sep="")))
      }
      HTML(w)
    })
    output$summary <- renderPrint({  
      print("your Alternative are:")

      for(i in 1:input$obs) {
        print(              
          input[[sprintf("a%d",i)]]
        )
      }
    })
    outputOptions(output, 'selectInputs', suspendWhenHidden=FALSE)
  })
})
}))

推荐答案

您的问题是每次单击按钮时都会重新生成所有按钮(即 input$aX).并且它们默认生成时没有值,这就是为什么当您读取它们时它们都是空值.

Your problem is that you regenerate all the buttons (so the input$aX) each time you click on the button. And they are generated without value by default, that's why when you read them they are all nulls.

例如,如果您抑制 output$selectInputs 代码中的循环,您可以看到自己的错误:(但现在它只允许您设置每个 aX 1 次.)

For example you can see your mistake if you supress the loop in your output$selectInputs code : (But now it only allow you to set each aX only 1 time.)

    output$selectInputs <- renderUI({
      if(!is.null(input$obs))
        print("w")
      w <- ""
      w <- paste(w, textInput(paste("a", input$obs, sep = ""), paste("a", input$obs, sep = "")))
      HTML(w)
    })

保留你的代码(然后保持所有按钮的重新生成),你应该在每个 textInput 的 value 参数中添加他的自己的值"(实际上是具有相同 id 的旧输入的值)value = input[[sprintf("a%d",i)]] :

Keeping your code (then keeping the regeneration of all the buttons), you should add to the value argument of each textInput his "own value" (in reality, the value of the old input with the same id) value = input[[sprintf("a%d",i)]] :

    output$selectInputs <- renderUI({
      w <- ""
      for(i in 1:input$obs) {
        w <- paste(w, textInput(paste("a", i, sep = ""), paste("a", i, sep = ""), value = input[[sprintf("a%d",i)]]))
      }
      HTML(w)
    })

这篇关于R 闪亮:如何构建动态 UI(文本输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆