我对 R 闪亮中的 req 和 validate 之间的区别有点困惑。我能看到的唯一真正的区别是 validate 向用户提供了一条消息。我正在构建一个界面,并使用了一堆隐藏的消息和条件语句。我想压缩我的代码并喜欢使用 validate 的想法。我只想在用户尝试单击按钮并尝试继续到 UI 的另一部分时显示我的消息。
我提供了一个简化版的代码,“成功”消息只会在 id 和协议按钮的文本输入被点击时显示。如果缺少一个或两个,条件面板将显示验证文本。
我担心在操作按钮内显示输出会破坏环境并本质上将其变成反应式环境。我在验证检查后使用了 req,因此除非为两者都提供了输入,否则不会显示成功消息。这是最好的方法吗?还是有更有效/更合适的方法?我主要担心的是,当我建立复杂性时,我会破坏应用程序。
library(shiny)
ui <- fluidPage(
textInput(inputId = "id",
label = 'Please enter your id'
),
checkboxInput("agree", label = "I agree", value = FALSE),
conditionalPanel(condition = "input.id == '' || !input.agree",
textOutput('error_msg')
),
actionButton("submit_info", "Submit"),
textOutput('success_msg')
)
server <- function(input, output) {
observeEvent(input$submit_info, {
output$error_msg <- renderText({
shiny::validate(
shiny::need(input$id != '', 'You must enter your id above to continue.'
),
shiny::need(input$agree, "You must agree to continue")
)
})
shiny::req(input$id)
shiny::req(input$agree)
output$success_msg <- renderText({"Success"})
})
}
shinyApp(ui = ui, server = server)