如何在JSX中输出句子并为匹配指定单词的文本着色?
解决方法
你只需要在map遍历的时候增加判断逻辑,匹配到目标单词时用带样式的标签包裹即可,同时要处理单词间的空格避免文字连在一起:
export default function App() { const defaultText = "Your partner for software innovations"; const colorText = "software"; const result = defaultText.split(" ").map((txt, index, arr) => { // 判断当前单词是否需要着色 if (txt === colorText) { return ( <span key={index} style={{ color: "red" }}> {txt} {/* 最后一个单词不加空格 */} {index !== arr.length - 1 ? " " : ""} </span> ); } // 普通单词直接返回,加空格分隔(最后一个除外) return `${txt}${index !== arr.length - 1 ? " " : ""}`; }); return <div className="App">{result}</div>; }
补充说明
- 如果项目用CSS类管理样式更规范,可以定义一个CSS类替代行内样式:
然后把.highlight-red { color: red; }<span>的style换成className="highlight-red"即可。 - 用
index作为key在这里是可行的,因为单词列表是静态的(来自后端固定文本),不会出现元素重新排序的情况。
内容的提问来源于stack exchange,提问作者someone
相关产品推荐
相关产品推荐

