react實現搜索關鍵字高亮的方法:1、利用正則從列表匹配到關鍵詞,再使用標簽包含關鍵詞;2、給標簽添加color屬性,然后使用react富文本渲染方式進行渲染實現快速搜索并且關鍵字高亮即可。
本教程操作環境:Windows10系統、react18.0.0版、Dell G3電腦。
react怎么實現搜索關鍵字高亮?
React實現快速搜索并且關鍵字高亮
需求:
點擊搜索按鈕,彈出模糊匹配列表。
下拉列表選擇選項,點擊后跳轉相應頁面關鍵字所在地。
思路:
利用正則從列表匹配到關鍵詞,再使用標簽包含關鍵詞,
給標簽添加color屬性,使用react富文本渲染方式進行渲染
js內容:
/** * 關鍵字變色 * @params content 內容 * @params keyword 關鍵詞 * @params tagName 標簽名 */ warpTag(content, keyword, tagName) { if (content === "No results") { return content } const a = content.toLowerCase() const b = keyword.toLowerCase() const indexof = a.indexOf(b) const c = indexof > -1 ? content.substr(indexof, keyword.length) : '' const val = `<${tagName} style="color:#FF6600;">${c}</${tagName}>` const regS = new RegExp(keyword, 'gi') console.log('regS',regS,keyword,val) console.log('regS222222',content,content.replace(regS, val)) return content.replace(regS, val) }
登錄后復制
jsx內容:
<span dangerouslySetInnerHTML={{__html: this.warpTag(item.n, keyword, "span")}}></span>
登錄后復制
推薦學習:《react視頻教程》