首页 > 解决方案 > 如何让 Shiny setInputValue 更改下拉选择?

问题描述

这些物种链接改变了基础值,species但下拉列表没有改变。我怎样才能解决这个问题?

library(shiny)
library(DT)

data(iris)
iris %>% rowwise %>% mutate(Species=as.character(actionLink(paste0('button_',Species), label = Species, onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' ))) -> iris


shinyApp(
  ui <- fluidPage(
    tags$script("
    Shiny.addCustomMessageHandler('set_species', function(value) {
    Shiny.setInputValue('species', value, {priority: 'event'});
    });"),
    selectInput("species",label = "Species",choices=c("setosa","virginica","versicolor")),
    DT::dataTableOutput("data")
  ),

  server <- function(input, output, session) {

    output$data <- DT::renderDataTable({
      DT::datatable(iris[c(1,75,150),], escape = FALSE, selection = 'none')
    })

    observeEvent(input$select_button, {
      selectedspecies <- strsplit(input$select_button, "_")[[1]][2]
      print(selectedspecies)
      session$sendCustomMessage("set_species", selectedspecies)
    })

  }
)

标签: shiny

解决方案


下面的代码将在按下链接时更改选择输入。它还将根据选择的内容过滤数据集。我们可以使用updateSelectInput来实现这一点,不需要自定义消息。

另请注意,setInputValue不设置 a 的值selectInput。它是 的别名onInputChange

(注意:如果您听说过一个名为 Shiny.onInputChange 的函数,那只是 Shiny.setInputValue 的一个更老、更令人困惑的名称;后者是在 Shiny v1.1 中引入的。尽管从未被正式记录或支持,但 Shiny.onInputChange 是/ 被广泛使用,我们不太可能很快将其删除,其行为与 Shiny.setInputValue 相同。)

https://shiny.rstudio.com/articles/communicating-with-js.html

library(shiny)
library(tidyverse)
library(DT)

data(iris)
iris <- iris %>%
  rowwise() %>%
  mutate(Species = as.character(
    actionLink(
      paste0("button_", Species),
      label = Species,
      onclick = 'Shiny.onInputChange(\"select_button\",  this.id);'
    )
  ))

shinyApp(
  ui <- fluidPage(
    selectInput(
      "species",
      label = "Species",
      choices = c("All", "setosa", "virginica", "versicolor")
    ),
    DT::dataTableOutput("data"),
    textOutput("myText")
  ),

  server <- function(input, output, session) {
    output$data <- DT::renderDataTable({
      data <- iris
      if (input$species != "All") {
        data <- data %>%
          filter(grepl(input$species, Species))
      }
      DT::datatable(data, escape = FALSE, selection = "none")
    })

    observeEvent(input$select_button, {
      selectedspecies <- strsplit(input$select_button, "_")[[1]][2]
      print(selectedspecies)
      updateSelectInput(session, "species", selected = selectedspecies)
    })
  }
)

推荐阅读