Как применить стиль css к действию - PullRequest
1 голос
/ 24 апреля 2020

У меня есть пример блестящего приложения, как показано ниже. Для того, чтобы actionButton с selectInput, мне нужно добавить style='margin-top:25px'. Пакет Shinywidgets содержит actionBttn виджетов со встроенным стилем. Например, мне нравится тот, у которого style='gradient'. Но мне интересно, как я могу использовать стиль css, чтобы добавить поле сверху, чтобы выровнять actionBttn с другим элементом?

library(shiny)
library(shinydashboard)
library(shinyWidgets)


ui <- dashboardPage(
    dashboardHeader(title = "example"),
    dashboardSidebar(),
    dashboardBody(
        box(width=12,

            column(width = 3, dateRangeInput("dateRange", "Date Range",
                                             start  = "2017-01-01",
                                             end    =  Sys.Date(),
                                             min    = "2001-01-01",
                                             max    = Sys.Date(),
                                             format = "mm/dd/yy",
                                             separator = " - ") ),

            column(width=3, selectizeInput(inputId = 'var', 
                                           label='Select variable',
                                           choices = c('cut', 'color'), 
                                           multiple=FALSE,
                                           options = list(
                                               maxItems = 1,
                                               placeholder = '',
                                               onInitialize = I("function() { this.setValue(''); }"))) ),

            column(width=1,  offset =2, actionButton('Apply', 'Apply', style='margin-top:25px') ),

            column(width=3,  actionBttn(
                inputId = 'clear',
                label = "Clear", 
                style = "gradient",
                color = "danger" ) )

        )
    )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

Ответы [ 2 ]

0 голосов
/ 24 апреля 2020

Чтобы добавить стиль к существующему элементу, созданному пакетом, иногда вам нужно обернуть этот элемент. Вот три подхода:

  1. Оберните сам элемент в div желаемым стилем. Может не работать для всех CSS элементов.

  2. Напишите свою собственную пользовательскую функцию, используя источник из нужного элемента. Здесь я использовал источник из https://github.com/dreamRs/shinyWidgets/blob/ac8134e944f91fdcc4490ace6d839c46e7df02ff/R/actionBttn.R#L63

  3. Добавьте несколько внешних CSS, предназначенных только для этого элемента. Это мой наименее любимый подход, потому что он перемещает логи c туда, где они на самом деле применяются, и вы должны отслеживать их для каждого элемента, который вы хотите изменить.


library(shiny)
library(shinyWidgets)


# new function for approach #2
actionBttn_with_style <- function(inputId, label = NULL, icon = NULL, style = "unite",
                       color = "default", size = "md", block = FALSE,
                       no_outline = TRUE, my_additional_style = "") {
  value <- shiny::restoreInput(id = inputId, default = NULL)
  style <- match.arg(
    arg = style,
    choices = c("simple", "bordered", "minimal", "stretch", "jelly",
                "gradient", "fill", "material-circle", "material-flat",
                "pill", "float", "unite")
  )
  color <- match.arg(
    arg = color,
    choices = c("default", "primary", "warning", "danger", "success", "royal")
  )
  size <- match.arg(arg = size, choices = c("xs", "sm", "md", "lg"))

  tagBttn <- htmltools::tags$button(
    id = inputId, type = "button", class = "action-button bttn", `data-val` = value,
    class = paste0("bttn-", style), 
    class = paste0("bttn-", size),
    class = paste0("bttn-", color), list(icon, label),
    class = if (block) "bttn-block",
    class = if (no_outline) "bttn-no-outline",
    style = my_additional_style
  )
  shinyWidgets:::attachShinyWidgetsDep(tagBttn, "bttn")
}

После того, как вы сделаете свою пользовательскую функцию кнопки, вы можете использовать ее, как actionBttn внутри вашего ui.

ui <- dashboardPage(
  dashboardHeader(
    title = "example"
    ),
  dashboardSidebar(),
  dashboardBody(

    # for approach #3, but this is far away from the button in the code
    htmltools::tags$head(
      htmltools::tags$style('button#clear_ext_css { margin-top:25px }')
    ),

    box(
      width = 12,

      column(
        width = 2,
        dateRangeInput(
          "dateRange",
          "Date Range",
          start  = "2017-01-01",
          end    =  Sys.Date(),
          min    = "2001-01-01",
          max    = Sys.Date(),
          format = "mm/dd/yy",
          separator = " - "
        )
      ),

      column(
        width = 1,
        actionButton('Apply', 'Apply', style = 'margin-top:25px')
      ),

      column(
        width = 3,
        # approach #1, just wrapping it in a styled div
        div(
          actionBttn(
            inputId = 'clear_div',
            label = "Clear with div",
            style = "gradient",
            color = "danger"
          ),
          style = 'margin-top:25px'
        )
      ),
      column(
        width = 3,
        # approach #2, custom function from above
        actionBttn_with_style(
          inputId = 'clear_fn',
          label = "Clear with custom function",
          style = "gradient",
          color = "danger",
          my_additional_style = 'margin-top:25px'
        )
      ),
      column(
        width = 3,
        # approach #3, but you don't see any custom logic here
        actionBttn(
          inputId = 'clear_ext_css',
          label = "Clear with external CSS",
          style = "gradient",
          color = "danger"
        )
      )


    )
  )
)

server <- function(input, output, session) {

}

shinyApp(ui, server)

enter image description here

0 голосов
/ 24 апреля 2020

Трудно сказать без вашего. css, но вы можете найти образец в здесь

...