2017-05-05 50 views
1

我希望能够移除一个UI元素,它是一个包含在fluidRow中的textInput,并将该元素(fluidRow和textInput)重新插入到UI中。但是,到目前为止,我没有取得任何成功。R将InsertUI插入FluidRow

removeUI按钮删除所有流体行,包括找到按钮的流体行。如果我尝试把它们放在一个单独的HTML部门中,它似乎没什么区别。或者如果它工作,textInput不再位于偏移量的流体行中。这是我的第一个闪亮的问题,所以请温柔我可能已经犯了一些明显的错误。

# Define UI 
    ui <- fluidPage(
      fluidRow(column(2,actionButton("rmv", "Remove UI"))), 
      fluidRow(column(2,actionButton("add", "Add UI"))), 
      tags$div(id='aTextBox', fluidRow(column(2,offset=6, 
                textInput("txt", "This is no longer useful")) 
              ) 
            ) 
) 


    # Server logic 
server <- function(input, output) { 

    observeEvent(input$rmv, { 
     removeUI(
     selector = "div:has(> #aTextBox)" 
    ) 
    }) 

    observeEvent(input$add, { 
    insertUI(
     selector = "#add", 
     where = "afterEnd", 
     ui = tags$div(id='aTextBox', fluidRow(column(2,offset=6, 
               textInput("txt", "This is no longer useful")) 
             ) 
           ) 
    ) 
    }) 
} 

    # Complete app with UI and server components 
    shinyApp(ui, server) 

回答

1

替换与两地的div:

tags$div(fluidRow(id='aTextBox', column(2,offset=6, 
              textInput("txt", "This is no longer useful")) 

编辑: 正如芭芭拉div(id = "placeholder")指出,可用于使文本框不放在同一div作为actionButton()

2

存在的主要问题是removeUI太宽泛。在这种情况下你想要的是直接做removeUI('#aTextBox')

但是,这段代码存在一些问题,即使它正常工作。这些大部分都与它允许用户多次点击“添加”的事实有关,但这会始终添加完全相同的元素,并且具有相同的id,这是无效的HTML。大多数浏览器起初不会抱怨,但它会回来咬你。为了解决这个问题,你可以在每次用户点击“添加”时改变ID,这样就不会有重复。或者,您可以跟踪该元素是否已经插入(但尚未删除)。你可以用一个简单的反应值来做到这一点。这似乎是你之后的行为,所以我在下面做了一个模拟(这段代码运行良好,但它可能会从一些重构和变量重命名中受益),还有一些更多的花俏和哨声(点击时会弹出通知“添加”或“删除”时不应该):

dynamicUI <- function(n) { 
    if (n != 0) { 
    showNotification("That input already exists", 
     type = "warning" 
    ) 
    return() 
    } else { 
    fluidRow(id = 'aTextBox', 
     column(2, offset = 6, 
     textInput("txt", "This is no longer useful") 
    ) 
    ) 
    } 
} 

# Define UI 
ui <- fluidPage(
    fluidRow(column(2, actionButton("rmv", "Remove UI"))), 
    fluidRow(column(2, actionButton("add", "Add UI"))), 
    div(id = "placeholder"), 
    dynamicUI(0) 
) 

# Server logic 
server <- function(input, output) { 
    n <- reactiveVal(1) 

    observeEvent(input$rmv, { 
    if (n() != 1) { 
     showNotification("Nothing to remove", 
     type = "error" 
    ) 
     return() 
    } 
    removeUI(selector = "#aTextBox") 
    n(0) 
    }) 

    observeEvent(input$add, { 
    insertUI(
     selector = "#placeholder", 
     where = "afterEnd", 
     ui = dynamicUI(n()) 
    ) 
    n(1) 
    }) 
} 

# Complete app with UI and server components 
shinyApp(ui, server)