【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;
相关推荐
mCell3 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip3 小时前
Node.js 子进程:child_process
前端·javascript
excel6 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel7 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼9 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping9 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙10 小时前
[译] Composition in CSS
前端·css
白水清风10 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix10 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780010 小时前
new、原型和原型链浅析
前端·javascript