react實現(xiàn)搜索關(guān)鍵字高亮的方法:1、利用正則從列表匹配到關(guān)鍵詞,再使用標簽包含關(guān)鍵詞;2、給標簽添加color屬性,然后使用react富文本渲染方式進行渲染實現(xiàn)快速搜索并且關(guān)鍵字高亮即可。
本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
react怎么實現(xiàn)搜索關(guān)鍵字高亮?
React實現(xiàn)快速搜索并且關(guān)鍵字高亮
需求:
點擊搜索按鈕,彈出模糊匹配列表。
下拉列表選擇選項,點擊后跳轉(zhuǎn)相應(yīng)頁面關(guān)鍵字所在地。
思路:
利用正則從列表匹配到關(guān)鍵詞,再使用標簽包含關(guān)鍵詞,
給標簽添加color屬性,使用react富文本渲染方式進行渲染
js內(nèi)容:
/** * 關(guān)鍵字變色 * @params content 內(nèi)容 * @params keyword 關(guān)鍵詞 * @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) }
登錄后復(fù)制
jsx內(nèi)容:
<span dangerouslySetInnerHTML={{__html: this.warpTag(item.n, keyword, "span")}}></span>
登錄后復(fù)制
推薦學(xué)習(xí):《react視頻教程》