最近有个需求,在一个react项目中,实现搜索关键字呈现高亮状态。这个在普通的html文件中还好操作些,在react项目中有点懵逼了,因为react项目中很少操作dom,有点无从下手。但最后还是实现了效果,如下:
首先来看看如何在react中操作dom,广大网友给出两种方案:
一:使用选择器:
1、引入react-dom
import ReactDom from 'react-dom'
2、给react节点设置id或类名等标识
<span id='tip'></span>
3、定义变量保存dom元素
var span = document.getElementById('tip')
4、通过ReactDom的findDOMNode()方法修改dom的属性
ReactDom.findDOMNode(span).style.color = 'red'
二:使用ref属性
1、给指定标签设置ref属性
<span ref='tip'></span>
2、通过this.refs.ref属性值来修改标签的属性
this.refs.tip.style.color = "red"
我用第二种方案来操作的:
import React from 'react'; import { Input } from 'antd'; const { Search } = Input; // 高亮测试 class Highlight extends React.Component { constructor(props) { super(props); this.state = { text:<p>writing to a TLS enabled socket, node::StreamBase::Write calls node::TLSWrap::DoWrite with a freshly allocated WriteWrap object as first argument. If the DoWrite method does not return an error, this object is passed back to the caller as part of a StreamWriteResult structure. This may be exploited to corrupt memory leading to a Denial of Service or potentially other exploits " + HTTP Request Smuggling in nodejs Affected versions of Node.js allow two copies of a header field in a http request. For example, two Transfer-Encoding header fields. In this case Node.js identifies the first header field and ignores the second. This can lead to HTTP Request Smuggling (https://cwe.mitre.org/data/definitions/444.html). " + OpenSSL - EDIPARTYNAME NULL pointer de-reference (High) This is a vulnerability in OpenSSL which may be exploited through Node.js. You can read more about it in https://www.openssl.org/news/secadv/20201208.txt</p> }; } findHighlight = (keyWord)=>{ const str=keyWord.replace(/^(s|xA0)+|(s|xA0)+$/g, ''); // eslint-disable-next-line react/no-string-refs const val= this.refs.tip.innerHTML; const content = this.searchdo(val, str); // eslint-disable-next-line react/no-string-refs this.refs.tip.innerHTML=content; }; searchdo=(content,keyWord)=>{ const keyWordArr = keyWord.split(' '); let re; for(let n = 0; n < keyWordArr.length; n +=1) { re = new RegExp(`${keyWordArr[n]}`,"gmi"); // eslint-disable-next-line no-param-reassign content = content.replace(re,`<span style="color:#0f0;${keyWordArr[n]}</span>`); } return content; }; render() { const { text} = this.state; return ( <div> <Search placeholder="请输入查找内容" onSearch={value => this.findHighlight(value)} style={{ 200 }} /> <br /> <br /> <div style={{ border:"1px solid #ccc", borderRadius:"4px", padding:"5px" }} ref="tip" > {text} </div> </div> ); } }
export default Highlight;
然后就实现了上面的效果,但是这只是最初步的,如果需要完善功能还需要自己进一步改造。