R Shiny中actionButton内strwrap处理的文本无法换行如何解决
问题表现
普通测试场景下,以下代码可输出按宽度10拆分的换行文本:
> HTML(paste0(strwrap('I saw a beautiful moon tonight',width=10), collapse="\n"))
控制台输出效果:
I saw a beautiful moon tonight
但将相同逻辑处理的文本传入actionButton作为按钮文本时,换行效果完全失效:
actionButton("df", HTML(paste0(strwrap('I saw a beautiful moon tonight',width=10), collapse="\n")))
实际渲染效果:
预期目标为按钮内文本按拆分规则显示为4行。
失效原因
HTML默认渲染规则下,普通文本中的换行符\n会被解析为普通空格,只有两种情况会识别\n为换行:
- 文本被
<pre>这类预格式化标签包裹 - 文本容器设置了
white-space: pre相关CSS样式actionButton内部的文本容器默认没有上述规则配置,因此直接传入带\n的HTML内容无法触发换行。
实现方案
任选以下一种方式即可实现按钮内文本按预期换行:
- 替换换行符为HTML原生换行标签
把拼接用的\n替换为<br/>,不需要额外配置样式,兼容性最好:library(shiny) ui <- fluidPage( actionButton( inputId = "df", label = HTML(paste0(strwrap('I saw a beautiful moon tonight', width = 10), collapse = "<br/>")) ) ) server <- function(input, output) {} shinyApp(ui, server) - 给按钮文本加预格式化样式
保留\n的写法,给文本包裹带white-space: pre样式的标签即可让浏览器识别换行符:library(shiny) ui <- fluidPage( actionButton( inputId = "df", label = HTML(paste0( "<span style='white-space: pre;'>", paste0(strwrap('I saw a beautiful moon tonight', width = 10), collapse = "\n"), "</span>" )) ) ) server <- function(input, output) {} shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者manu p
相关产品推荐
相关产品推荐

