React實現(xiàn)模糊搜索和關鍵字高亮的示例代碼
背景
公司需要一個可視化頁面,作為Redis查詢展示的工具,方便同事進行快速檢索。
要求將后端返回的報文,完整展現(xiàn)在識圖中,并且可以提供關鍵詞檢索和關鍵詞點亮的功能,以便快速定位關鍵詞。
整體效果預覽:

主要功能
點擊搜索:返回的大字符串形式報文被組裝成JSON的格式,點擊搜索匹配相應字段, 并高亮顯示
點擊區(qū)分大小寫:模糊匹配 OR 精確匹配
查找下一個:被選中的字段,往下移動一個,下一個的背景顏色切換為另一高亮色
解決
- 匹配到的文本,動態(tài)插入樣式
- 使用正則解決匹配問題
- 點擊下一個時,動態(tài)切換類名和背景色
代碼實現(xiàn)
僅僅貼出主要代碼
DOM
...
<Input
value={this.state.txt}
placeholder="請輸入檢索內(nèi)容"
onChange={e => this.setState({txt: e.target.value})}
></Input>
<Button onClick={this.dispatchHighLightText}>
搜索
</Button>
...
<CheckBos
checked={this.state.isCheck}
onChange={e => this.setState({isCheck: e.target.checked})}
>
區(qū)分大小寫
</CheckBos>
...
<Button
onClick={this.searchToNext}
>
查找下一個
</Button>
...
<pre
dangerouslySetInnerHTML={{__html: this.state.information}}
contentEditable
>
{/*動態(tài)插入html的容器*/}
</pre>
CSS
// 每個匹配到的都有的類名
.highLight{
background-color: #a9a9a9;
}
// 點擊下一個時的類名,默認為第一個
.current{
background-color: #32aaf8;
}
JS
點擊搜索時
colorIndex = 0; // 初始化高亮標記
_information = ''; // 文本備份
dispatchHighLightText = () => {
const {txt} = this.state; // 檢索內(nèi)容
if(!txt){
message.warning("請先輸入查詢條件");
return;
}
// 重置高亮標記
colorIndex = 0;
const regex = new RegExp(txt, this.state.isCheck ? 'g' : 'gi'); // 不勾選 => 模糊匹配
// 由于每次插入樣式都會污染文本,所以每次都需要從備份文本中重新渲染
const newInformation = _information;
const hightLightTxt = newInformation.replace(regex, (match,index) => `<span class="highLight"> ${match} </span>`);
this.setState({infomation: hightLightTxt}, () => {
// 視圖更新渲染然后,獲取到dom
let highLightEle = document.querySelectorAll('.highLight');
this.updateHeight(highLightEle)
}); // render
}
// 點亮目標關鍵字
updateHeight = (highLightEle) => {
highLightEle.forEach((element, index) => {
if(index === colorIndex){
element.classList.add('current');
element.scrollIntoView({ behavior: 'smooth', block: 'center'});
}else{
element.classList.remove('current');
}
})
}
點擊 “下一個”
searchToNext = () => {
let highLightEle = document.querySelectorAll('.highLight');
if(heighLightEle.length){
colrIndex = (colorIndex + 1 + highLightEle.length) % highLightEle.length;
this.updateHeight(highLightEle)
}
}
反思
- 本來想用偏移量window.getSelection 和 document.createRange 以及相關api模擬富文本實現(xiàn)光標跳轉(zhuǎn)定位的,可是發(fā)現(xiàn)偏移量不好確定(小菜雞)
- 每次渲染的時候需要拿新的備份的文本進行替換,不要用臟數(shù)據(jù)
- pre標簽可以很好的保留文本原來的樣式,不能用textarea
- dangerouslySetInnerHTML接收的是一個對象
以上就是React實現(xiàn)模糊搜索和關鍵字高亮的示例代碼的詳細內(nèi)容,更多關于React模糊搜索和關鍵字高亮的資料請關注腳本之家其它相關文章!
相關文章
React中useRef與useState的使用與區(qū)別
本文介紹了React中兩個常用的鉤子useRef和useState,包含比較它們的功能并提供示例來說明它們的用法,具有一定的參考價值,感興趣的可以了解一下2024-11-11
react-router-dom v6版本跳轉(zhuǎn)路徑的實現(xiàn)方法
這篇文章主要介紹了react-router-dom v6版本跳轉(zhuǎn)路徑的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
react-router JS 控制路由跳轉(zhuǎn)實例
這篇文章主要介紹了react-router JS 控制路由跳轉(zhuǎn)實例,react實現(xiàn)路由可以直接使用react-router。有興趣的可以了解一下2017-06-06

