下面的代码在用户编辑rhandsontable单元格后更改其背景色。
library(shiny)
library(rhandsontable)
ui <- fluidPage(
titlePanel ('Give it a try and make changes!'),
mainPanel(rHandsontableOutput('table'))
)
server <- function(input, output, session) {
df <- data.frame(SYMBOLS = c('AAPL', 'ALRM', 'AMZN', 'BABA', 'CRM', 'CSCO',
'FB'),
NAMES = c('APPLE', 'ALARM.com', 'AMAZON', 'ALIBABA',
'SALESFORCE', 'CISCO', 'FACEBOOK'),
NOTE = c('sale', '', 'buy', '', '', '', 'watch'))
output$table <- renderRHandsontable(
rhandsontable(df))
rv <- reactiveValues(row = c(), col = c())
observeEvent(input$table$changes$changes, {
rv$row <- c(rv$row, input$table$changes$changes[[1]][[1]])
rv$col <- c(rv$col, input$table$changes$changes[[1]][[2]])
output$table <- renderRHandsontable({
rhandsontable(hot_to_r(input$table), row_highlight = rv$row,
col_highlight = rv$col) %>%
hot_cols(
renderer = "
function(instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
if (instance.params) {
hrows = instance.params.row_highlight;
hrows = hrows instanceof Array ? hrows : [hrows];
hcols = instance.params.col_highlight;
hcols = hcols instanceof Array ? hcols : [hcols];
}
for (let i = 0; i < hrows.length; i++) {
if (instance.params && hrows[i] == row && hcols[i] == col) {
td.style.background = 'pink';
}}
}"
)
})
})
}
shinyApp(ui, server)
每次更改单元格时,
-
此单元格的行索引(
input$table$changes$changes[[1]][[1]]
)及其列索引(
input$table$changes$changes[[1]][[2]]
)附加到反应变量
rv$row
和
rv$col
分别地
-
使用reactive变量再次呈现rHandsontable(
rv
)这包括迄今为止已更改的所有单元格的索引,最后,
-
A.
for
javascript渲染器中的循环遍历
rv
一次一对,针对表中的所有列和行。如果行和列索引都匹配,则此单元格的背景色将更改为粉红色。