问题
I have the following in server.R
shinyServer(function(input, output) {
# builds a reactive expression that only invalidates
# when the value of input$goButton becomes out of date
# (i.e., when the button is pressed)
ntext <- eventReactive(input$goButton, {
input$n
})
output$nText <- renderText({
ntext()
})
})
and the following in ui.R
shinyUI(pageWithSidebar(
headerPanel("actionButton test"),
sidebarPanel(
numericInput("n", "N:", min = 0, max = 100, value = 50),
br(),
actionButton("goButton", "Go!"),
p("Click the button to update the value displayed in the main panel.")
),
mainPanel(
verbatimTextOutput("nText")
)
))
My goal is to make the go action button disappear once it is clicked five times and give a pop up window warning if clicked less than five times.
回答1:
As @daattali is saying, shinyjs
make this really easy, you can do it like this:
library(shiny)
library(shinyjs)
ui <- shinyUI(
fluidPage(
useShinyjs(),
sidebarPanel(
actionButton('btn','Click me')
),
mainPanel(
verbatimTextOutput("nText")
)
)
)
server <- shinyServer(function(input,output,session){
n <- 0
makeReactiveBinding('n')
observeEvent(input$btn, {
if(n < 5){
info('Msg')
} else if(n > 5){
hide('btn')
}
n <<- n + 1
})
output$nText <- renderText({
n
})
})
shinyApp(ui=ui,server=server)
Here's how you would hide the button without using shinyjs:
library(shiny)
ui <- shinyUI(
fluidPage(
tags$head(
tags$style(
HTML('#num{display: none;}')
)
),
useShinyjs(),
sidebarPanel(
conditionalPanel(
condition = "input.num < 5",
actionButton('btn','Click me')
),
numericInput('num','',0)
),
mainPanel(
verbatimTextOutput("nText")
)
)
)
server <- shinyServer(function(input,output,session){
n <- 0
makeReactiveBinding('n')
observeEvent(input$btn, {
n <<- n + 1
updateNumericInput(session,'num',value=n)
})
output$nText <- renderText({
n
})
})
shinyApp(ui=ui,server=server)
And finally without using observeEvent:
library(shiny)
ui <- shinyUI(
fluidPage(
tags$head(
tags$style(
HTML('#num{display: none;}')
)
),
useShinyjs(),
sidebarPanel(
conditionalPanel(
condition = "input.num < 5",
actionButton('btn','Click me')
),
numericInput('num','',0)
),
mainPanel(
verbatimTextOutput("nText")
)
)
)
server <- shinyServer(function(input,output,session){
n <- 0
makeReactiveBinding('n')
observe({
input$btn
isolate({
n <<- n + 1
updateNumericInput(session,'num',value=n)
})
})
output$nText <- renderText({
n
})
})
shinyApp(ui=ui,server=server)
回答2:
You don't need to define a reactive n
. It is already the value of input$btn
.
library(shiny)
library(shinyjs)
ui <- shinyUI(
fluidPage(
useShinyjs(),
sidebarPanel(
actionButton('btn','Click me')
),
mainPanel(
verbatimTextOutput("nText")
)
)
)
server <- shinyServer(function(input,output,session){
observe({
if(input$btn < 5){
info('Msg')
} else {
hide('btn')
}
})
output$nText <- renderText({
input$btn
})
})
shinyApp(ui=ui,server=server)
来源:https://stackoverflow.com/questions/33590653/modify-shiny-action-button-once-it-is-clicked