[英]I'm creating a table in in which the data is being gotten from a JSON file. this is the code
[英]Styling a specific word in a data gotten from an api which is populated on a screen
在将带有“搜索值”的 a 发送到 API 后,该“搜索值”会在数据库中搜索该值并使用包含该值的数据进行响应。 我想在响应中突出显示给定的词或搜索值。 响应填充到 UI
<center>
{Object.keys(Disp).map((key, i) => (
<center key={i} className="PublicationCard">
<span> {key}</span>
<a href={"https://www." + Disp[key]}> View Publication</a>
</center>
))}
</center>
关键是一个句子,但我想加粗关键中的一个词例如,假设关键是“关于监督人工智能的讨论”并且搜索查询是人工智能,我想做的就是加粗搜索查询是 UI 中的“人工智能”
也许你可以创建一个 function 来生成多个 span 标签。
function GenerateSpan({ text, search }) {
const reg = new RegExp(`(.*)(${search})(.*)`, "g")
const array = [...text.matchAll(reg)]
if (array.length > 0) {
return array[0].slice(1).map((textPart, index) => {
return <span key={index} className={textPart === search ? "highlight" : ""}>{textPart}</span>
})
} else {
return <span>{text}</span>
}
}
并在您的代码中使用:
<GenerateSpan text=key search="Supervised"/>
然后添加样式为“class”高亮
.highlight{
font-weight: bold
}
所以最后:
<center>
{Object.keys(Disp).map((key, i) => (
<center key={i} className="PublicationCard">
<GenerateSpan text=key search="Supervised"/>
<a href={"https://www." + Disp[key]}> View Publication</a>
</center>
))}
</center>
使用RegExp
的示例运行速度更快,但这里有一种更简单的方法。
function Highlighter({ highlight = '', children: text }) {
const index = text.toLowerCase().indexOf(highlight.toLowerCase());
if (index >= 0 && highlight.length) {
const beforeHighlight = text.substring(0, index);
const highlightedPart = text.substring(index, index + highlight.length);
const afterHighlight = text.substring(index + highlight.length);
return (
<highlight-text>
{beforeHighlight}
<span>{highlightedPart}</span>
{afterHighlight}
</highlight-text>
);
}
return <>{text}</>;
}
export default Highlighter;
并像这样使用它:
<Highlighter highlight={'Recursion'}>
{'Recursion a misunderstood topic'}
</Highlighter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.