让我们从最小的示例开始:
library(shiny)
library(shinyjs)
ui <- fixedPage(
shinyjs::useShinyjs(),
extendShinyjs(script = "www/hideShowFile.js", functions = c("showByDefault")),
fluidRow(
column(12,
selectInput("scenario", "Choose scenario", c("A", "B", "C"))
)),
a(id = "hideShow", "Show/Hide content", href = "#"),
fluidRow(
div(id="hideable",
br(),
htmlOutput("hideable_text")),
br()
),
br(),
fluidRow(htmlOutput("always_visible"))
)
server <- function(input, output) {
output$hideable_text <- renderUI({
HTML(paste0("<p>This is scenario ", input$scenario, "</p>" , "<p>This will not always be visible. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>"))
})
output$always_visible <- renderUI({
HTML("<p>This is always visible.</p>")
})
shinyjs::onclick("hideShow",
shinyjs::toggle(id = "hideable", anim = TRUE))
observeEvent(input$scenario, js$showByDefault())
}
# Run the application
shinyApp(ui = ui, server = server)
app.R
所在目录的结构如下:
shiny_project
|- app.R
|- www/
|- hideShowFile.js
hideShowFile.js
包含以下代码(我从WWW3School的网站上获取):
function shinyjs.showByDefault() {
console.log("I have been called!")
var x = document.getElementById("hideable");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
如您在代码中所见,我想显示和隐藏Shiny应用程序的一部分(div
中的id="hideable"
)。但是,div
被隐藏不仅取决于所单击的锚点(id="hideShow"
),还取决于是否选择了新方案。
作为一个例子:假设我选择了B方案。我不会隐藏文本,而是继续下一个场景-C。回到B,然后单击“隐藏”按钮。然后我切换到A,然后显示(当前未实现的内容)文本。如果我切换到A(使用提供的代码),该文本将被隐藏,并且我必须单击按钮以显示它。我希望如果方案已更改并且以前隐藏了文本,则文本会自动显示。
我已经检查了控制台(可以通过在Shiny应用程序上单击“检查”来访问该控制台),它说:
TypeError: undefined is not a function (evaluating 'shinyjs.showByDefault(params)')
(anonymous function)
_sendMessagesToHandlers
(anonymous function)
_sendMessagesToHandlers
dispatchMessage
onmessage