Как избежать дублирования insertUI в R Shiny? - PullRequest
1 голос
/ 08 мая 2019

В этом коде

if (interactive()) {
  # Define UI
  ui <- fluidPage(
    actionButton("add", "Add UI"),
    actionButton("remove", "Remove UI"),
    tags$div(id = "add")
  )

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

    # adding UI
    observeEvent(input$add, {
      insertUI(
        selector = "#add",
        where = "afterEnd",
        ui = 
          div(
            textInput("txt", "Insert some text"),
            id="textinput"
          )
      )
    })

    # removing UI
    observeEvent(input$remove, {
      removeUI(selector = "#textinput")
    })
  }

  shinyApp(ui, server)
}

Я хочу, чтобы динамический интерфейс отображался только один раз . Независимо от количества нажатий кнопок «Добавить».

Однако, после того, как вы нажмете кнопку «Удалить пользовательский интерфейс», вы сможете снова добавить динамический интерфейс (также один раз)

enter image description here

enter image description here

1 Ответ

1 голос
/ 08 мая 2019

Вы можете сделать это, используя conditionalPanel и observe.

library(shiny)

if (interactive()) {
  # Define UI
  ui <- fluidPage(
    actionButton("add", "Add UI"),
    actionButton("remove", "Remove UI"),
    conditionalPanel(condition = "input.add > 0", 
                     uiOutput("textbox"))
  )

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

    # adding UI
    observe({
      if (!is.null(input$add)) {
        output$textbox <- renderUI({
          div(
            textInput("txt", "Insert some text"),
            id="textinput"
          )
        })
      }
    })

    # removing UI
    observeEvent(input$remove, {
      removeUI(selector = "#textinput")
    })
  }

  shinyApp(ui, server)
}

РЕДАКТИРОВАТЬ - без conditionalPanel.

library(shiny)

if (interactive()) {
  # Define UI
  ui <- fluidPage(
    actionButton("add", "Add UI"),
    actionButton("remove", "Remove UI"),
    uiOutput("textbox"))


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

    # adding UI
    observeEvent(input$add, 
      output$textbox <- renderUI({
        div(
          textInput("txt", "Insert some text"),
          id="textinput"
          )
      })

    )

    # removing UI
    observeEvent(input$remove, {
      removeUI(selector = "#textinput")
    })
  }

  shinyApp(ui, server)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...