【React】搜索时高亮被搜索选中的文案

文章目录

代码实现

函数封装:

ts 复制代码
export function highlightKeyword(input: string, keyword: string | undefined) {
  if (!keyword || !input || !input.includes(keyword)) return input;

  const startIndex = input.indexOf(keyword);

  return React.createElement('span', null, [
    input.substring(0, startIndex),
    React.createElement(
      'span',
      {
        style: {
          backgroundColor: 'rgba(255, 255, 0, 0.8)',
          color: 'black',
        },
      },
      keyword,
    ),
    input.substring(startIndex + keyword.length),
  ]);
}

使用案例:

js 复制代码
import React from 'react';
import { Tree } from 'antd';

const { DirectoryTree } = Tree;

const treeData = [
  {
    title: '目录1',
    key: '1',
    children: [
      { title: '目标目录', key: '1-1' }, // 此节点名称会显示为红色
      { title: '子目录2', key: '1-2' },
    ],
  },
  {
    title: '目录2',
    key: '2',
  },
];

const App = () => {
  const [searchText, setSearchText] = useState('')
  return <div>
  			<Input placeholder="请输入搜索文案" onChange={(e)=>setSearchText(e.target.value)} />
  			<DirectoryTree
    			treeData={treeData}
    			titleRender={(nodeData) => {
      				return (
        				<span style={{ color: isMatched ? 'red' : 'inherit' }}>
          					{searchText ? highlightKeyword(nodeData.title, searchText) : nodeData.title}
        				</span>
      				);
    			}}
  			/>
  		</div>
};

export default App;
相关推荐
新中地GIS开发老师17 分钟前
零基础WebGIS开发入门 | GeoJSON数据持久化
前端·javascript·gis·webgis·三维gis开发
blns_yxl34 分钟前
正则驱动实时表单验证(HTML+CSS+JS+正则)
javascript·css·html
sunywz1 小时前
【c#】 Web Deploy一键发布,IIS部署全流程
开发语言·前端·c#
宁&沉沦1 小时前
Chrome 扩展 Manifest 字段版本支持一览(全量)
前端·后端·编辑器
乖孩子1 小时前
Service Worker + IndexedDB 实践
前端
浮生望1 小时前
BFF架构实战:用Express+SSE为Vue3搭建安全的流式对话中间层
前端
Quz1 小时前
QML 与 JavaScript 交互方式:内联函数、外部文件、信号槽与工作线程
javascript·qt
拾年2752 小时前
React 组件通信完全指南 —— 从 Todo App 搞懂父子组件那点事
react.js
先吃饱再说2 小时前
React 组件通信:从 Props 单向传递到自定义事件
前端·react.js·前端框架
swipe2 小时前
05|(前端转后全栈)不手写一堆 SQL,后端怎么操作数据库?MyBatis-Plus 入门
前端·后端·全栈