使用 dangerouslySetInnerHTML
<div
dangerouslySetInnerHTML={{ __html: this.highListRender(text,field)}}
>
</div>
方法,解决返回参数存在html标签一并渲染的情况,将< 替换为 <
highListRender = (item,field) =>{
item = item+''
// item 需要替换的 field 业务代码可忽略
if (
// 业务判断可忽略 this.state.highList 为需要高亮的字符串的map集合
item != null &&
item !== "" &&
this.state.highList != null &&
this.state.highList.has(field)
) {
const highStart = "_highStart&&;_highStart"
const highEnd = "_highEnd&&;_highEnd"
for (const str of this.state.highList.get(field)) {
// 关键位置
item = item.replace(str, `${highStart}${str}${highEnd}`)
}
}
// 修复返回值含有html关键字展示问题
if (item != null && item !== '' ) {
item = item.replace(/</g, '<')
item = item.replace(/_highStart&&;_highStart/g, '<span style="background:yellow">')
item = item.replace(/_highEnd&&;_highEnd/g, '</span>')
}
return item
}