【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;
相关推荐
老李笔记17 分钟前
VUE element table 列合并
javascript·vue.js·ecmascript
滿18 分钟前
Vue3 Element Plus 表格默认显示一行
javascript·vue.js·elementui
好了来看下一题20 分钟前
TypeScript 项目配置
前端·javascript·typescript
江城开朗的豌豆24 分钟前
Vue的双向绑定魔法:如何让数据与视图‘心有灵犀’?
前端·javascript·vue.js
江城开朗的豌豆26 分钟前
Vue权限控制小妙招:动态渲染列表的优雅实现
前端·javascript·vue.js
@菜菜_达1 小时前
CSS a标签内文本折行展示
前端·css
霸王蟹1 小时前
带你手写React中的useReducer函数。(底层实现)
前端·javascript·笔记·学习·react.js·typescript·前端框架
wen's1 小时前
React 中的 useCallback 入门指南:是真需要,还是假怪?
react.js
托尼沙滩裤1 小时前
【Vue3】实现屏幕共享惊艳亮相
前端·javascript·vue.js
啃火龙果的兔子1 小时前
前端八股文-vue篇
前端·javascript·vue.js