首页 > 解决方案 > 对从屏幕上填充的 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 中的“人工智能”

标签: javascriptcssreactjs

解决方案


也许您可以创建一个函数来生成多个跨度标签。

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>

推荐阅读