shiny - 如何让 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)
})
}
)
解决方案
下面的代码将在按下链接时更改选择输入。它还将根据选择的内容过滤数据集。我们可以使用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)
})
}
)
推荐阅读
- c# - 如何将 SELECT MAX 语句从 SQL 转换为 LINQ 到 SQL?
- java - 使用 Kafka Streams 对数据进行窗口化并同时处理每个窗口
- python - 在 Python 2.7 中使用 Selenium 选择按钮
- angular - Ionic 3 - 打开应用程序时如何重定向roottab
- java - gpg --list-keys 为空,但文件解密 bouncycastle 加密文件
- java - Android,围绕圆轴滚动点
- java - 在 Java 中使用反射调用超类构造函数
- java - Android Studio 看不到按钮
- popup - 在 Flutter 上从后台打开/显示/弹出应用程序
- python-3.x - 使用 gmail api 密钥时出现密钥错误