gpt4 book ai didi

javascript - 如何在 ReactJS 中用另一个字符串和不同的颜色替换一个字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:15 24 4
gpt4 key购买 nike

我有一个从数组映射的字符串,我使用正则表达式返回特定文本。我希望这个特定的文本在呈现时具有不同的颜色。然而,当前的方法失败了,因为它不允许我只在纯 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>
);
})}

最佳答案

感谢@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>
);
})}

关于javascript - 如何在 ReactJS 中用另一个字符串和不同的颜色替换一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com