最近有個需求,在一個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;background-color:#ff0">${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;
然後就實現了上面的效果,但是這只是最初步的,如果需要完善功能還需要自己進一步改造。