如何在data.frame中存储tippy提示框并通过reactable渲染?
解决Reactable中Tippy提示框渲染问题
你的代码无法正常显示带图片的提示框,主要有几个问题需要调整:
- 提示框里的图片没有用正确的
<img>标签渲染,直接放链接只会显示文本 - 用了htmltools的内部私有函数
htmltools:::as.character.shiny.tag.list(),容易出问题,应该用公开方法处理标签转字符 - Tippy的JS依赖可能没正确加载,需要确保UI里引入相关资源
修正后的代码如下:
library(shiny) library(tidyverse) library(tippy) library(htmltools) ui <- fluidPage( titlePanel("Reactable and pop-ups"), # 显式加载tippy依赖 useTippy(), reactableOutput("table") ) server <- function(input, output) { df <- data.frame( dog_name = c("Fred", "Joe"), dog_pic = c( "https://images.pexels.com/photos/406014/pexels-photo-406014.jpeg", "https://images.pexels.com/photos/39317/chihuahua-dog-puppy-cute-39317.jpeg" ) ) %>% rowwise() %>% mutate( # 用img标签生成图片元素,用renderTags处理tippy标签并保留依赖 dog_name = tippy( dog_name, img(src = dog_pic, style = "width: 200px; height: auto;") ) %>% renderTags() %>% .$html ) %>% ungroup() output$table <- renderReactable( reactable(df, columns = list( dog_name = colDef(html = TRUE, name = "Dog"), dog_pic = colDef(show = FALSE) ) ) ) } shinyApp(ui = ui, server = server)
关键修改说明:
- 在UI中添加
useTippy(),确保Tippy的JavaScript和CSS资源正确加载 - 提示框内容改用
img(src = dog_pic)生成图片,还可以通过style控制图片大小 - 用
htmltools::renderTags()处理tippy生成的标签,它会把标签转成HTML字符串,同时自动处理依赖(这里我们只取html部分,因为依赖已经通过useTippy加载) - 替换内部私有函数,用公开方法更稳定
内容的提问来源于stack exchange,提问作者Gion Mors
相关产品推荐
相关产品推荐

