【React】搜索时高亮被搜索选中的文案
文章目录
- 代码实现
代码实现
函数封装:
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),]);
}
使用案例:
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)} /><DirectoryTreetreeData={treeData}titleRender={(nodeData) => {return (<span style={{ color: isMatched ? 'red' : 'inherit' }}>{searchText ? highlightKeyword(nodeData.title, searchText) : nodeData.title}</span>);}}/></div>
};export default App;