2017-05-05 46 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)