[英]Highlight React JSX element for array of keywords
I am new to React and am attempting to highlight the text in a JSX expression based on the keywords from an array.我是 React 新手,正在尝试根据数组中的关键字突出显示 JSX 表达式中的文本。
return <RightWrapper>
{value.sort((a, b) => a - b.id).map(transcript => <p key={transcript.id}>{transcript.createdAt+" "+ transcript.Transcription +" "} </p> )}
</RightWrapper>
searchWords={["tech", "deck", "financial"]}
You can create a set of search words, Check if that text is available in a set or not, You can do using an array also but it's slower compared to the set.您可以创建一组搜索词,检查该文本是否在一组中可用,您也可以使用数组,但与该组相比速度较慢。
const set = new Set(["tech", "deck", "financial"]);
const arr = value.sort((a, b) => a.id - b.id)
return (
<RightWrapper>
{
arr.map(transcript => (
<p
key={transcript.id}
style={{
color: set.has(transcript.id) ? 'red' : 'black'
}}
>{transcript.createdAt + " " + transcript.Transcription + " "} </p>
))
}
</RightWrapper>
)
This should solve your problem,这应该可以解决您的问题,
const set = new Set(["tech", "deck", "financial"]);
const arr = value.sort((a, b) => a.id - b.id);
function createMarkup(transcript) {
const words = ["tech", "deck", "financial"];
let str = `${transcript.createdAt} ${transcript}`;
words.forEach((word) => {
if (str.includes(word)) {
str = str.replaceAll(word, `<span class="highlight">${word}</span>`);
}
});
return { __html: str };
}
return (
<RightWrapper>
{arr.map((transcript) => (
<p
dangerouslySetInnerHTML={createMarkup(transcript.Transcription)}
key={transcript.id}
></p>
))}
</RightWrapper>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.