如何只动态为文本的特定部分着色

时间:2019-12-16 05:53:12

标签: javascript reactjs

我有一个reactjs网络应用程序,我只需要对选定的句子显示特定的颜色。我有两个状态,分别存储很难和非常难的句子数组,这些句子是我们从api动态获取的。我只需要分别用黄色和红色为难和非常难的句子涂上颜色,其余的文本则用默认颜色涂上颜色。

假设这是全文

It's the possibility of having a dream come true that makes life interesting. He stepped down, trying not to look long at her, as if she were the sun, yet he saw her, like the sun, even without looking. I cannot fix on the hour, or the spot, or the look or the words, which laid the foundation. Satan trembles when he sees the weakest saint upon their knees

然后api扫描句子并发送上一段中非常困难的句子

{
  "hard": [
    "It's the possibility of having a dream come true that makes life interesting",
    "I cannot fix on the hour, or the spot, or the look or the words, which laid the foundation.",
  ]
 "very_hard": [
    “He stepped down, trying not to look long at her, as if she were the sun, yet he saw her, like the sun, even 
     without looking.”
  ]
}

这是代码:

 states={
          hardArray: [],
          vhardArray: []
   };

     {enteredText.split(". ").map(word => {
          if (this.state.vhardArray.includes(word)) {
            return <span className="vhardColor">{word}</span>;
          }

          if (this.state.hardArray.includes(word)) {
            return <span className="hardColor">{word}</span>;
          }

          return [word, ". "];
        })}

但是,当检查DOM元素时,在困难的句子和非常困难的句子周围没有span标签,因此很可能没有将CSS分配给它们。如何正确分配CSS?

2 个答案:

答案 0 :(得分:2)

我将建议您使用replace和regex而不是使用split。它更加灵活和持久。您必须循环一次。

它可以简化为以下示例,您可以在JSX中使用删除“”。懒于设置react项目或stackbliz

    const vtext = [":D", ";)"]
    const htext = [":>"]
    const compileEmoji = (emj) => {
        if(vtext.indexOf(emj) > -1) return '<span class="vtext">{emj}</span>'
        if(htext.indexOf(emj) > -1) return '<span class="htext">{emj}</span>'
        return emj
    }
    const buildEmoji = (text = "") => {
        return text.replace(/(\S+)(\s+)/g, function(w, mat1, mat2) {
            return `${compileEmoji(mat1)}${mat2}`
        })
    }
    console.log(buildEmoji("This is something :> new :D hu hahaha ;) "))

答案 1 :(得分:0)

您可以将CSS动态添加到文档中,例如:

let vhardColor = document.createElement('style');
        vhardColor.innerHTML = `
          .vhardColor { 
            color: blue;
         } `;
        document.head.appendChild(vhardColor);