【问题标题】:How to replace a string with another and with a different colour in ReactJS?如何在 ReactJS 中用另一个和不同颜色替换一个字符串?
【发布时间】:2020-01-07 00:32:39
【问题描述】:

我有一个从数组映射的字符串,并且我使用了一个正则表达式来返回特定的文本。我希望这个特定的文本在呈现时具有不同的颜色。然而,当前的方法失败了,因为它不允许我在纯 javascript 中设置字符串的样式。有没有办法解决这个问题,以便替换可以使用不同颜色的新文本。

理想情况下,最终结果应该是这样的

@user This is text

其中@user 是蓝色,其余的是黑色

{this.state.dataReplies.map((n, i) => {
            var re = /@(\S+)\b/g;
            let oldstr = n.description.match(re);
            console.log(oldstr);
            let newstr = oldstr.style.colour = "#0066ff";
            let str = n.description.replace(oldstr, newstr);
    return (
      <p>{str}</p>
    );
})}

【问题讨论】:

  • 您不能设置纯字符串的样式。相反,只需将所选内容包装在具有所需样式的 &lt;span/&gt; 中。
  • 完美运行。谢谢。

标签: javascript css regex reactjs


【解决方案1】:

感谢@Jayce444 的解决方案:

{this.state.dataReplies.map((n, i) => {
            var re = /@(\S+)\b/g;
            let oldstr = n.description.match(re);
            let str = n.description.replace(oldstr, "");
    return (
      <p> <span style={{color: "#0066ff"}}>{oldstr}</span> {str}</p>
    );
})}

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    相关资源
    最近更新 更多