javascript - 对从屏幕上填充的 api 获取的数据中的特定单词进行样式设置
问题描述
在将带有“搜索值”的 API 发送到 API 后,该 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 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"/>
然后为类“highlight”添加样式
.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>
推荐阅读
- ruby-on-rails - NameError,添加到表时未初始化的常量
- dropbox-api - Python Dropbox API v2 - users_get_space_usage() 不等于来自 Dropbox 应用程序的值
- python-3.x - rasa : asyncio - 操作工作时从未检索到任务异常
- sql - Microsoft Access 如何计算一个值和该值的所有排列在字段中列出的次数?
- c++ - Indy 10 中是否有相当于 Indy 9 的 WriteBuffer() 的功能?
- excel - 使工作表名称与单元格值相同
- redux - axios 查询字符串 thunk + graphql
- r - 为什么这个函数没有很好的精度?
- algorithm - 求解while循环时间复杂度算法
- sql - 错误 [42000] [IBM] [System I Access ODBC 驱动程序] [DB2 for i5/OS]SQL0104 令牌 _ 无效