• 使用React Hooks实现表格搜索功能


    React Hooks是React 16.8版本引入的新特性,它的作用是为函数组件提供了状态管理和副作用处理的能力。

    在React之前,函数组件被限制在只能使用无状态的函数组件,无法使用状态生命周期方法。Hooks的引入解决了这个限制,使得函数组件可以拥有和类组件相似的功能。

    React Hooks的主要作用包括:

    • 状态管理:通过useState Hook,函数组件可以定义和使用状态。useState返回一个状态值和一个更新该状态值的函数,并且在组件重新渲染时能够保持状态的持久性。这使得函数组件能够保存和更新自己的状态,使得组件变得更加灵活和可复用。

    • 副作用处理:通过useEffect Hook,函数组件可以处理副作用操作,例如订阅数据、请求数据、操作DOM等。useEffect接收一个副作用函数和一个依赖数组作为参数,它会在每次组件渲染完成后执行副作用函数。这使得函数组件能够在需要时执行副作用操作,并且可以在组件卸载时清理副作用。

    • 上下文访问:通过useContext Hook,函数组件可以访问React的上下文(Context)。上下文提供了一种在组件树中共享数据的方式,而不需要通过逐层传递props。useContext接收一个上下文对象作为参数,并返回当前上下文的值。这使得函数组件能够更方便地使用上下文中的数据。

    • 自定义Hook:除了React提供的Hooks,开发者还可以自定义自己的Hooks。自定义Hook是一个函数,以"use"开头,并可以使用其他Hooks。通过自定义Hook,开发者可以将组件逻辑抽象为可复用的函数,使得组件变得更加简洁和可维护。

    总体而言,React Hooks的作用是为函数组件提供了更多的功能和灵活性,使得函数组件能够更好地管理状态、处理副作用和访问上下文,从而简化了组件的开发和维护。它们使得函数组件成为了开发React应用的首选方式,并且在实际项目中得到了广泛的应用和验证。

    表格搜索功能

    d75423ca125d8b57c0e09e500def787c.png

    在很多表格中,数据量是一次性直接返回的,如果增加一个搜索输入框+搜索按钮的话有点笨重,可以直接在表头位置增加搜索按钮

    在表格所在组件中实现这个功能直接编写代码就行了,但是如果有多个表格需要使用到该功能,就需要将它提取出来

    代码编写

    创建了一个名为searchInput的引用,用于获取搜索输入框的DOM元素。

    然后,使用useState定义了两个状态变量:searchText和searchedColumn。

    • searchText用于存储搜索关键词

    • searchedColumn用于存储当前正在搜索的列

    定义了handleSearch方法和handleReset方法。

    • handleSearch方法用于处理搜索操作,它接收选中的关键词selectedKeys、确认函数confirm和数据索引dataIndex作为参数。在这个方法中,我们调用了confirm函数来关闭搜索框,并更新searchText和searchedColumn的值。

    • handleReset方法用于重置搜索操作,它接收清除过滤器函数clearFilters作为参数,用于清空搜索关键词并重置搜索状态

    getColumnSearchProps

    定义了getColumnSearchProps方法,它接收三个参数:dataIndex、title和index2。这个方法返回一个包含多个属性和方法的对象,用于配置表格搜索功能。

    filterDropdown

    返回一个包含搜索输入框和两个按钮的div元素。

    • 查找按钮触发handleSearch方法

    • 重置按钮触发handleReset方法

    filterIcon

    包含搜索图标的Icon组件

    根据搜索状态来决定图标的颜色,当进行搜索时,图标会变为蓝色

    onFilter

    实现具体的搜索逻辑。

    根据dataIndex和index2参数来判断记录中对应字段的值是否包含搜索关键词。

    如果传入了index2,则比对那一列中的

    record[dataIndex][index2]

    不传入则是

    record[dataIndex]

    根据获取数据的层级来判断是否需要使用index2

    使用index2的原因是,某些数据的层级较深,比如数据是「identity.uri」

    1. {
    2.    title: '录制Identity',
    3.    dataIndex: 'identity.uri',
    4.    key: 'identity',
    5.    width: 200,
    6.    ...getColumnSearchProps('identity''录制Identity''uri'),
    7.  },

    不使用index2的数据是:

    1. {
    2.   title: '录制Identity',
    3.   dataIndex: 'originUri',
    4.   key: 'originUri',
    5.   width: 200,
    6.   ...getColumnSearchProps('originUri''录制Identity'),
    7. },

    onFilterDropdownVisibleChange

    当搜索框显示时自动选中搜索框

    render

    渲染表格中的每一行数据。

    如果当前列是正在搜索的列,它会使用react-highlight-words组件对匹配的关键词进行高亮显示。

    使用

    1. import useTableColumnSearch from '@/hooks/useTableColumnSearch';
    2. const { getColumnSearchProps } = useTableColumnSearch();
    3. // 表格的Columns
    4. {
    5.   title: '录制Identity',
    6.   dataIndex: 'identity.uri',
    7.   key: 'identity',
    8.   width: 200,
    9.   ...getColumnSearchProps('identity''录制Identity''uri'),
    10. },

    总结

    使用该方式后可以:简化组件逻辑,方便复用

    完整代码

    1. import React, { useRef, useState } from 'react';
    2. import { Input, Button, Icon } from 'antd';
    3. import Highlighter from 'react-highlight-words';
    4. /*
    5.  * 表格搜索
    6.  * */
    7. const useTableColumnSearch = () => {
    8.   const searchInput = useRef();
    9.   const [searchText, setSearchText] = useState('');
    10.   const [searchedColumn, setSearchedColumn] = useState('');
    11.   const handleSearch = (selectedKeys, confirm, dataIndex) => {
    12.     confirm();
    13.     setSearchText(selectedKeys[0]);
    14.     setSearchedColumn(dataIndex);
    15.   };
    16.   const handleReset = (clearFilters) => {
    17.     clearFilters();
    18.     setSearchText('');
    19.   };
    20.   /*
    21.    * @param dataIndex: 搜索的字段
    22.    * @param title: 搜索的字段中文名
    23.    * @param index2: 搜索的字段中的子字段
    24.    * */
    25.   const getColumnSearchProps = (dataIndex, title, index2 = null) => ({
    26.     filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
    27.       8 }}>
    28.         
    29.           ref={searchInput}
    30.           placeholder={`搜索${title}`}
    31.           value={selectedKeys[0]}
    32.           onChange={(e) => setSelectedKeys(e.target.value ? [e.target?.value.trim()] : [])}
    33.           onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
    34.           style={{ width: 188, marginBottom: 8, display: 'block' }}
    35.         />
    36.         type="primary" onClick={() => handleSearch(selectedKeys, confirm, dataIndex)} icon="search" size="small" style={{ width: 90, marginRight: 8 }}>
    37.           查找
    38.         
    39.          handleReset(clearFilters)} size="small" style={{ width: 90 }}>
    40.           重置
    41.         
    42.       
  •     ),
  •     filterIcon: (filtered) => type="search" style={{ color: filtered ? '#1890ff' : undefined }} />,
  •     onFilter: (value, record) => {
  •       if (index2) {
  •         return record[dataIndex][index2]?.toString().toLowerCase().includes(value.toLowerCase());
  •       }
  •       return record[dataIndex]?.toString().toLowerCase().includes(value.toLowerCase());
  •     },
  •     onFilterDropdownVisibleChange: (visible) => {
  •       if (visible) {
  •         setTimeout(() => searchInput.current.select());
  •       }
  •     },
  •     render: (text) => {
  •       return searchedColumn === dataIndex ? '#ffc069', padding: 0 }} searchWords={[searchText]} autoEscape textToHighlight={text?.toString()} /> : text;
  •     },
  •   });
  •   return { getColumnSearchProps };
  • };
  • export default useTableColumnSearch;
  • 相关阅读:
    ES6 入门教程 4 字符串的扩展 4.6 实例:模板编译 & 4.7 标签模板 & 4.8 模板字符串的限制
    OPPO 后端二面,凉凉。。。
    分布式之消息队列精讲
    ThreadLocal为什么会出现内存泄漏,你真的知道吗?
    机器学习-集成学习(模型融合)方法概述
    【git】新电脑(Windows)中Git配置SSH公钥
    支付宝电脑网站支付,异步通知
    Windows 下基于 MikTeX 的 Latex 环境配置小记
    【mysql篇-基础篇】通用语法1
    IO多路转接之select和poll
  • 原文地址:https://blog.csdn.net/weixin_37786060/article/details/132769650