最近有個需求,在一個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\n" +
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).\n" +
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={{ width: 200 }}
/>
<br />
<br />
<div
style={{
border:"1px solid #ccc",
borderRadius:"4px",
padding:"5px"
}}
ref="tip"
>
{text}
</div>
</div>
);
}
}
export default Highlight;
然后就實現了上面的效果,但是這只是最初步的,如果需要完善功能還需要自己進一步改造。
