首页 > 解决方案 > 拆分功能以突出显示 React 中的搜索词

问题描述

我有一些数据,我映射并试图突出显示输入到字段中的搜索词。我有这个小部分,我将字符串值(我正确验证了控制台日志)传递给我的 splitResult 函数。它应该将该字符串拆分为多个片段,对它们进行索引,然后返回带有突出显示部分的字符串......我如何返回这些片段?示例:(item.title 应该显示而不是)如果没有足够的代码来理解这个沙箱可能会有所帮助.. 搜索应用

//split the search term
  const splitResult = (result) => {
    result.split(new RegExp(`(${searchTerm})`, `gi`)).map((piece, index) => {
      return <span
          key={index}
          style={{
            background: piece.toLowerCase() === searchTerm.toLocaleLowerCase() ?    
            "YELLOW" : "TRANSPARENT",
          }}
        >
          {piece} //<--is this right?//
        </span>
    });
};

//some of the rendering
<div key={item.index}>
     <div>{splitResult(item.title)}</div>
     {item.content.map((i, index) => {
     return <div key={index}>{i.text}</div>;
     })}
     <div className={styles.searchLink}
           onClick={() => {
           context.setCurrentSlide(item.index);}} 
          >Go To This Slide {item.index}
     </div>
 </div>

标签: javascriptreactjsregexsplitarray.prototype.map

解决方案


推荐阅读