如何将rhandsontable中的逻辑值列显示为UI端可编辑复选框
问题根因
原有代码中hot_cols全局指定了TextRenderer,覆盖了rhandsontable默认对逻辑值列的复选框渲染逻辑,才导致bool列只显示文本、无法编辑。
修改后可运行代码
library(rhandsontable) DF = data.frame(val = 1:10, bool = TRUE, big = LETTERS[1:10], small = letters[1:10], dt = seq(from = Sys.Date(), by = "days", length.out = 10), stringsAsFactors = FALSE) col_highlight = 2 row_highlight = c(5, 7) rhandsontable(DF, col_highlight = col_highlight, row_highlight = row_highlight, width = 550, height = 300) %>% # 单独给逻辑列指定checkbox类型,默认开启编辑权限 hot_col(col = "bool", type = "checkbox") %>% hot_cols(renderer = " function(instance, td, row, col, prop, value, cellProperties) { // 区分列类型调用对应渲染器,复选框列不使用TextRenderer if (cellProperties.type === 'checkbox') { Handsontable.renderers.CheckboxRenderer.apply(this, arguments); } else { Handsontable.renderers.TextRenderer.apply(this, arguments); } tbl = this.HTMLWidgets.widgets[0] hcols = tbl.params.col_highlight hcols = hcols instanceof Array ? hcols : [hcols] hrows = tbl.params.row_highlight hrows = hrows instanceof Array ? hrows : [hrows] if (hcols.includes(col) && hrows.includes(row)) { td.style.background = 'red'; } else if (hcols.includes(col)) { td.style.background = 'lightgreen'; } else if (hrows.includes(row)) { td.style.background = 'pink'; } return td; }")
改动说明
- 新增
hot_col(col = "bool", type = "checkbox")配置:显式指定bool列的渲染类型为复选框,rhandsontable对checkbox类型的列默认开启编辑权限,点击即可勾选/取消勾选。 - 调整渲染器逻辑:在渲染函数中先判断列的类型,复选框列调用默认的
CheckboxRenderer渲染,其他列继续用原有的TextRenderer,既保留了原本的行列高亮效果,也不会覆盖复选框的渲染逻辑。
内容的提问来源于stack exchange,提问作者Phlybo
相关产品推荐
相关产品推荐

