react 搜索关键字高亮

js 部分
import React, { Component } from 'react'
import './index.less';
export default class index extends Component {
constructor(props) {
super(props);
this.state={
cmpList: [ // 企业名字列表
'小米科技有限责任公司',
'小米数字科技有限公司',
'小米有品科技有限公司',
'小米之家科技有限公司',
'重庆长安汽车股份有限公司',
'重庆长安工业(集团)有限责任公司',
'长安责任保险股份有限公司',
'长安银行股份有限公司',
'英大长安保险经纪有限公司'
],
showCmpList: [], // 搜索列表
cmpValue: '', // 搜索栏输入值
}
}
inputChnage = (e) => {
e.persist()
let { cmpValue, cmpList, showCmpList} = this.state;
cmpValue = e.target.value;
// 过滤出包含关键字的企业名称
showCmpList = cmpList.filter(v => v.indexOf(cmpValue) !== -1)
.map(v => // 把匹配上的关键字加上 css 标签。原生里面 className 会被转成 class, 所以这里直接添加 class。
v.replace(cmpValue, "<span class='highlight'>" + cmpValue + "</span>")
)
if (!cmpValue) showCmpList=[]; // 如果关键字为空,清空搜索列表。
this.setState({ cmpValue, showCmpList});
}
render() {
return (
<div className='search-box'>
<div className='search-top-box'>
<input onChange={this.inputChnage} value={this.state.cmpValue} type="text" placeholder='请输入课程' />
<button>提交</button>
</div>
<div className='search-bottom-box'>
{
this.state.showCmpList.map((v,i) => (
// 把字符串用 html 显示
<p className='item' key={i} dangerouslySetInnerHTML={{ __html: v}}></p>
))
}
</div>
</div>
)
}
}
css 部分
.search-box { width: 240px; .search-bottom-box { width: 100%; height: 200px; border: 1px solid yellow; p { .highlight { color: rgba(10,118,245,.8); } } } }

浙公网安备 33010602011771号