【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;
相关推荐
万少4 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站6 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名8 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫9 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊9 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter9 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折9 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_9 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码19 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial9 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js