【问题标题】:Rhandsontable conditional formatting- How to highlight rows based on specific attribute value?Rhandsontable 条件格式 - 如何根据特定属性值突出显示行?
【发布时间】:2017-12-02 11:21:57
【问题描述】:

我想根据值对整行应用颜色突出显示并保留 rhandsontable 的复选框功能。在下面的简单示例中,我希望第 3 行为粉红色,第 4 行为绿色。

library(rhandsontable)

DF = data.frame( bool = TRUE,val = 1:10, big = LETTERS[1:10],
                small = letters[1:10],
                stringsAsFactors = FALSE)

###Checkboxes not Present/Entire row not highlighted
rhandsontable(DF, readOnly = FALSE, width = 750, height = 300) %>%
  hot_cols(renderer = "
           function (instance, td, row, col, prop, value, cellProperties) {
           Handsontable.renderers.NumericRenderer.apply(this, arguments);
            if (value == 'C') {
           td.style.background = 'pink';
           } else if (value == 'D') {
           td.style.background = 'green';
           }
           }")

####Checkboxes Present
rhandsontable(DF, readOnly = FALSE, width = 750, height = 300)

【问题讨论】:

    标签: javascript r shiny handsontable rhandsontable


    【解决方案1】:

    问题是您使用了 NumericRenderer,它试图将应用的列转换为数字。我的解决方案可能不是最佳的,但它可以完成工作。

    library(rhandsontable)
    
    DF = data.frame( bool = TRUE,val = 1:10, big = LETTERS[1:10],
                     small = letters[1:10],
                     stringsAsFactors = FALSE)
    
    # Text Renderer
    text_renderer <- "
      function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        # This is the column which you want to check for coloring
        var col_value = instance.getData()[row][2]
        if (col_value == 'C') {
          td.style.background = 'pink';
        } else if (col_value == 'D') {
          td.style.background = 'green';
        }
      }"
    
    # Renderer for the bool column
    bool_renderer <- "
      function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
        var col_value = instance.getData()[row][2]
        if (col_value == 'C') {
          td.style.background = 'pink';
        } else if (col_value == 'D') {
          td.style.background = 'green';
        }
      }
    "
    # Entire row highlighted and checkbox attribute preserved
    rhandsontable(DF, readOnly = FALSE, width = 750, height = 300) %>%
      hot_col(col = c(2, 3, 4), renderer = text_renderer) %>%
      hot_col("bool", renderer = bool_renderer)
    

    诀窍是你创建了两个渲染器:

    • 专门为您的 bool 列设计的 CheckboxRenderer
    • 其余列的 TextRenderer。

    instance.getData()[row][2] 检索行索引row 处的大列的值。因此,渲染器会检查每一行 if 语句中的条件是否为 TRUE。

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多