在前端实现关键词检索后的高亮展示以及前后端接口设计时,通常有几种可选方案。以下是一些推荐的实现方案,分别涵盖了前后端设计和前端的高亮展示:
方案 1:后端返回带有标记的文本
-
后端接口设计:
- 在后端处理搜索逻辑时,直接将匹配到的
keyword
用特定标记(例如<mark>
标签或自定义标记符号)包裹,返回的数据中包含带有标记的title
和description
。 - 返回的数据结构可能类似这样:
[ { "title": "This is a <mark>keyword</mark> example", "description": "Find the <mark>keyword</mark> in this description" } ]
- 在后端处理搜索逻辑时,直接将匹配到的
-
前端渲染:
- 前端可以直接使用
dangerouslySetInnerHTML
渲染后端返回的标记内容,来展示高亮效果。
const renderTextWithHighlight = (text: string) => { return <span dangerouslySetInnerHTML={ { __html: text }} />; }; const SearchResults = ({ results }) => { return results.map(item => ( <div key={item.title}> <h3>{renderTextWithHighlight(item.title)}</h3> <p>{renderTextWithHighlight(item.description)}</p> </div> )); };
- 前端可以直接使用
方案 2:前端处理高亮显示(后端只返回纯文本)
-
后端接口设计:
- 后端只返回普通的
title
和description
字段,不带任何高亮标记。返回结构例如:[ { "title": "This is a keyword example", "description": "Find the keyword in this description" } ]
- 后端只返回普通的
-
前端渲染:
- 前端接收数据后,自己在渲染时根据
keyword
进行字符串匹配
- 前端接收数据后,自己在渲染时根据