【发布时间】:2021-12-27 16:52:24
【问题描述】:
我正在构建一个shiny 应用程序,并且将在多个页面上具有相同的radio button 输入,这将改变页面上显示的内容。我将这些单选按钮放在一个模块中,这样我就不必在多个地方重现该代码。它们都有一组静态的choices,但我希望它们在整个应用程序中都保持相同的selected 值。这意味着每次更改页面时,都会选择与以前相同的值。如果我在一个页面上选择A,那么所有其他页面也会选择A,直到我在任何其他页面上选择不同的选项。
到目前为止,我的任何尝试都没有运气。 This explanation 似乎接近我正在寻找的东西,但我无法让它发挥作用。在下面的应用程序中,我觉得我应该能够向modServer 函数传递一个反应值,该值会将关联的radio buttons 更新为相同的selected 值。如果我可以基于input$tmp 进行单个模块更新,我想我应该能够在模块的多次迭代中复制它。
编辑:更新了代码。应用程序现在可以检查以将模块外部的 input$tmp 的值视为自身和反应值。也在模块内作为输入以及新的反应值。
新问题:为什么没有将这些变量显示为反应变量?这一定是observeEvent 在modServer 中不起作用的原因。 renderText 显示这些值正在更新,但不会触发 updateRadioGroupButtons。
library(shiny)
library(shinyWidgets)
# UI module
modUI <- function(id){
ns <- NS(id)
tagList(
shinyWidgets::radioGroupButtons(
inputId = ns("radio"),
choices = c('A', 'B', 'C', 'D'),
selected = 'A'),
uiOutput(ns('modtest')),
uiOutput(ns('modtest2'))
)
}
# Server module
modServer <- function(id, .selected){
moduleServer( id, function(input, output, session){
ns <- session$ns
mod_rval <- reactive({ .selected() })
output$modtest <- renderText({
paste('mod_rval() is:', mod_rval(), 'and is reactive: ', is.reactive(mod_rval()))
})
output$modtest2 <- renderText({
paste('.selected() is:', .selected(), 'and is reactive: ', is.reactive(.selected()))
})
observeEvent(.selected(), {
shinyWidgets::updateRadioGroupButtons(
session,
inputId = ns("radio"),
choices = c('A', 'B', 'C', 'D'),
selected = .selected()
)
})
})
}
# APP
ui <- fluidPage(
selectInput('tmp', 'tmp : input value', choices = c('A','B','C','D')),
modUI(id='mod1'),
uiOutput('test'),
uiOutput('test2')
)
server <- function(input, output, session) {
# functioning.
rval <- reactive({input$tmp})
modServer(id = 'mod1', .selected = rval)
output$test <- renderText({
paste('rval() is: ', rval(), 'and is reactive: ', is.reactive(rval()))
})
output$test2 <- renderText({
paste('input$tmp is: ', input$tmp, 'and is reactive: ', is.reactive(input$tmp))
})
}
shinyApp(ui, server)
【问题讨论】:
标签: r shiny module shinywidgets