R Shiny selectizeInput搜索多关键词时选项关键词被截断问题
R Shiny selectizeInput 多关键词搜索时选项内容被截断的解决方法
在使用Shiny的selectizeInput组件时,输入多个关键词(比如“producer price”)会出现选项里的匹配关键词被截断甚至完全删除的问题,示例代码如下:
library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel( selectizeInput(inputId = "id_category", label = "Category (multiple answers possible)", multiple = TRUE, choices = c("Producer price oil", "Producer price pulp", "Producer price oat", "Import price oil")), ), mainPanel() ) ) server <- function(input, output) { } shinyApp(ui, server)
问题原因
这是selectize默认的高亮匹配机制导致的,多关键词搜索时,默认逻辑会错误替换匹配到的文本片段,破坏原选项内容。
解决方案
方法一:自定义渲染逻辑(保留高亮效果)
通过options参数自定义选项的渲染函数,手动处理关键词高亮,确保原文本完整保留:
library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel( selectizeInput( inputId = "id_category", label = "Category (multiple answers possible)", multiple = TRUE, choices = c("Producer price oil", "Producer price pulp", "Producer price oat", "Import price oil"), options = list( render = I('{ option: function(item, escape) { var text = item.label; // 拆分搜索关键词 var query = this.$control.val().trim().split(/\\s+/); // 逐个关键词添加高亮标签 query.forEach(function(word) { if (word) { var regex = new RegExp(escapeRegExp(word), 'gi'); text = text.replace(regex, '<span class="selectize-highlight">$&</span>'); } }); return '<div>' + text + '</div>'; }, item: function(item, escape) { return '<div>' + escape(item.label) + '</div>'; } }'), setup = I('function() { // 定义正则特殊字符转义函数 window.escapeRegExp = function(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }; }') ) ) ), mainPanel() ) ) server <- function(input, output) { } shinyApp(ui, server)
这个方案会保留关键词的高亮效果,同时保证原选项文本不被截断。
方法二:关闭默认高亮(快速解决)
如果不需要高亮效果,可以直接关闭selectize的默认高亮功能:
library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel( selectizeInput(inputId = "id_category", label = "Category (multiple answers possible)", multiple = TRUE, choices = c("Producer price oil", "Producer price pulp", "Producer price oat", "Import price oil"), options = list(highlight = FALSE) ), mainPanel() ) ) server <- function(input, output) { } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者panuffel
相关产品推荐
相关产品推荐

