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

问题描述 投票:1回答:1

我有一个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?

javascript reactjs
1个回答
0
投票

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

let vhardColor = document.createElement('style');
        vhardColor.innerHTML = `
          .vhardColor { 
            color: blue;
         } `;
        document.head.appendChild(vhardColor);
© www.soinside.com 2019 - 2024. All rights reserved.