我想模塊化一個複雜的Shiny應用程序,我有一個conditionalPanel
應該只顯示給定的輸入狀態。R帶條件面板和反應的閃亮模塊
之前我做了一切模塊化,輸入和conditionalPanel均在ui.R
,我可以用這樣的參考輸入:
conditionalPanel("input.select == 'Option one'", p('Option one is selected'))
現在,我已經模塊化的東西,訪問輸入更復雜。我認爲以下是做到這一點的方法,但它不起作用。 (在這裏,我的東西結合成一個單一的獨立腳本):
library(shiny)
## Module code for 'selectorUI' and 'selector'
selectorUI <- function(id) {
ns <- NS(id)
selectizeInput(inputId = ns('select'),
label = 'Make a choice:',
choices = c('Option one', 'Option two'))
}
selector <- function(input, output, session) {
reactive(input$select)
}
## Main app
ui <- shinyUI(fluidPage(
selectorUI('id1'),
conditionalPanel(condition = "output.selected == 'Option one'", p('Option one is selected.'))
))
server <- shinyServer(function(input, output, session) {
output$selected <- callModule(selector, 'id1')
})
shinyApp(ui = ui, server = server)
我認爲這應該工作,但它沒有 - 如果我再拍參考output$selected
在主界面部分它只:
ui <- shinyUI(fluidPage(
selectorUI('id1'),
textOutput('selected'), ## Adding just this one line makes the next line work
conditionalPanel(condition = "output.selected == 'Option one'", p('Option one is selected.'))
))
不幸的是,當然這會產生textOutput('selected')
的結果的不良影響。我只能猜測這個原因起作用是因爲它以某種方式觸發了反應,而JavaScript引用本身沒有。
任何想法我應該如何讓這個條件面板正常工作?
謝謝。
編輯:原來並不是一個真正的錯誤:https://github.com/rstudio/shiny/issues/1318。在下面看到我自己的答案。
但也請注意,我實際上喜歡接受答案中給出的renderUI
解決方案比我的原始conditionalPanel
方法更好。
這確實有效,但是這不違反模塊化的概念嗎?您必須知道模塊的代碼在內部調用輸入'select'才能構建'id1-select'。 –
是的,你是對的 - 我更新了我的文章。 –
我認爲這確實是一個錯誤。我通過https://github.com/rstudio/shiny/issues/1318提供了一個更簡單的例子。我更喜歡'renderUI'解決方案,因爲'conditionalPanel'依賴於'display:none'風格來隱藏內容,而'renderUI'方法只是給出一個空的div。謝謝你寫了。 –