【问题标题】:Delete corresponding input element when using removeUI使用removeUI时删除对应的输入元素
【发布时间】:2019-01-02 01:56:17
【问题描述】:

问题

在删除removeUI 的控件时,如何删除/使相应的input 元素无效?

您可以在下面的reprex 中看到,即使在删除textInput 之后,input$x 仍然是“真实的”。理想情况下,我可以告诉shiny input$x 不再有效,任何依赖input$xreactives 都将其视为空。

更新

到目前为止阅读答案,我想我并不清楚我想要实现什么。我真的很想知道是否可以在概念上“取消”input$x。在这种情况下,我不必担心有什么东西会破坏生产线。


Reprex

library(shiny)

ui <- fluidPage(
  div(textInput("x", "Text"), id = "killme"),
  actionButton("del", "Delete"),
  verbatimTextOutput("out")
)

server <- function(input, output) {
  output$out <- renderPrint(req(input$x))
  observeEvent(input$del, removeUI("#killme"))
}

shinyApp(ui, server)

【问题讨论】:

  • removeUI("#out")?还是我误会了?
  • out 只是为了说明input$x 仍然存在。所以我不关心output$out 本身,但我真的很想取消input$x
  • 我不知道,但也许session$sendInputMessage("x", NULL)
  • 好主意,但不幸的是没有工作:(

标签: r shiny


【解决方案1】:

您可以将reactiveValues 用于打印输出,并在删除 div 时将其分配为 NULL。不知道有没有更优雅的解决方案。

library(shiny)

ui <- fluidPage(
  div(textInput("x", "Text"), id = "killme"),
  actionButton("del", "Delete"),
  verbatimTextOutput("out")
)

server <- function(input, output) {
  textX <- reactiveValues(x = NULL)

  observe({
    textX$x = input$x
  })

  observeEvent(input$del, {
    textX$x = NULL
    removeUI("#killme")
    })

  output$out <- renderPrint({
    req(textX$x)
    textX$x
    })
}

shinyApp(ui, server)

【讨论】:

  • 感谢您的解决方法。但是,我真的很感兴趣是否可以在概念上取消input$x。我将编辑我的问题以使其更清楚。无论如何感谢您的建议。 +1
【解决方案2】:

这个SO question 展示了如何使输入无效。有了这个解决方案就变成了:

ui <- fluidPage(
  tags$script("
    Shiny.addCustomMessageHandler('resetValue', function(variableName) {
      Shiny.onInputChange(variableName, null);
    });
  "),
  div(textInput("x", "Text"), id = "killme"),
  actionButton("del", "Delete"),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  output$out <- renderPrint(req(input$x))
  observeEvent(input$del, {
    removeUI("#killme")
    session$sendCustomMessage("resetValue", "x")})

}

shinyApp(ui, server)

感谢您的回答,因为只有通过讨论,我才能使我的问题更清楚,并且能够找到正确的解决方案。


使用library(shinyjs)的短格式:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(debug = TRUE),
  div(textInput("x", "Text"), id = "killme"),
  actionButton("del", "Delete"),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  output$out <- renderPrint(req(input$x))
  observeEvent(input$del, {
    removeUI("#killme")
    runjs('Shiny.onInputChange("x", null)')
  })

}

shinyApp(ui, server)

【讨论】:

    猜你喜欢
    • 2018-12-02
    • 2017-07-21
    • 2023-03-22
    • 1970-01-01
    • 2017-03-20
    • 2021-12-11
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多