如何在React/Next.js中为特定文本添加自定义样式实现搜索关键词高亮
表格搜索关键词高亮实现方案
方案1:整单元格高亮(满足基础条件加类需求)
你原有代码的问题是JSX中执行JS表达式需要用{}包裹,且重复声明了description对应的td标签,修正后的代码如下:
<Table className={styles.table}> <thead> <tr> <th>Description</th> <th>Date and time</th> <th>Debit</th> <th>Credit</th> <th>Balance</th> </tr> </thead> <tbody> {input.length < 1 ? displayTransactions.map(transaction => ( <tr key={transaction._id}> <td>{transaction.description}</td> <td>{transaction.date}</td> <td className={styles.debit}>- ${transaction.debit}</td> <td className={styles.credit}>+ ${transaction.credit}</td> <td>{transaction.balance}</td> </tr> )) : output.map(transaction => ( <tr key={transaction._id}> {/* 条件判断给td加高亮类 */} <td className={transaction.description.includes(input) ? styles.highlight : ''}> {transaction.description} </td> <td>{transaction.date}</td> <td className={styles.debit}>- ${transaction.debit}</td> <td className={styles.credit}>+ ${transaction.credit}</td> <td>{transaction.balance}</td> </tr> ))} </tbody> </Table>
对应样式文件补充:
.highlight { background-color: #fff3cd; color: #856404; }
方案2:仅高亮匹配的关键词(体验更优,只标亮用户输入的对应字符)
首先在组件内定义文本处理工具函数:
// 关键词高亮处理,兼容特殊字符输入、不区分大小写匹配 const highlightKeyword = (text, keyword) => { if (!keyword.trim()) return text; // 转义正则特殊字符避免报错 const escapeKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regExp = new RegExp(`(${escapeKeyword})`, 'gi'); return text.split(regExp).map((part, idx) => { return part.toLowerCase() === keyword.toLowerCase() ? <span key={idx} className={styles.keywordHighlight}>{part}</span> : part; }); };
修改表格td部分的代码:
<td> {highlightKeyword(transaction.description, input)} </td>
对应样式文件补充:
.keywordHighlight { background-color: #ffeb3b; font-weight: bold; padding: 0 2px; border-radius: 2px; }
内容的提问来源于stack exchange,提问作者Amr Shawki
相关产品推荐
相关产品推荐

