[英]R Shiny InsertUI into fluidRow
我希望能够删除UI元素,它是fluidRow中包含的textInput,然后将该元素(fluidRow和textInput)重新插入到UI中。 但是,到目前为止,我还没有成功。
removeUI按钮删除了所有fluidRows,包括找到按钮的那些。 如果我尝试将它们放在单独的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)
那里的主要问题是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)
用以下两个地方替换div:
tags$div(fluidRow(id='aTextBox', column(2,offset=6,
textInput("txt", "This is no longer useful"))
编辑:正如Barbara div(id = "placeholder")
所指出的,可以使用该文本框,以便将文本框放置在与actionButton()
相同的div中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.