作为一名前端工程师,我时常需要在项目中处理复杂的选择场景,比如组织架构选择、权限分配等。普通的下拉框已经无法满足需求,而 Ant Design 的 TreeSelect 组件虽然强大,但如何让它支持动态加载数据、树形结构选择,还能与穿梭框的效果结合起来?这篇文章将带你基于 React、TypeScript 和 Antd,打造一个功能强大且易用的 TransferComSelect 组件,解决这些痛点。
为什么需要这个组件?
在实际业务中,我们经常会遇到以下需求:
- 树形数据展示: 需要展示层级结构,比如公司部门树。
- 动态加载: 数据量大时,按需加载子节点以提升性能。
- 多选与穿梭: 支持多选,并清晰展示已选内容。
- 灵活性: 可切换“只选本级”或“包含子级”的选择模式。
基于这些需求,我们将实现一个结合 TreeSelect 的树形选择组件,支持动态加载和自定义交互。
核心代码实现
以下是 TransferComSelect 组件的核心代码,我会逐步拆解它的实现逻辑:
.switch {
display: flex;
background-color: #fff;
padding: 5px 10px;
width: 100%;
margin-bottom: 5px;
>span {
margin-right: 5px;
}
}
.tree {
height: 300px;
overflow-y: auto;
scrollbar-width: none;
/* Firefox */
-ms-overflow-style: none;
}
.tree::-webkit-scrollbar {
display: none;
}
import React, { useState, useEffect, useCallback } from 'react';
import { TreeSelect, Switch, Spin, Empty } from 'antd';
import {debounce} from 'lodash'; // 引入 lodash 的防抖函数
import './index.less';
interface TreeDataNode {
key: string;
value: string;
title: string;
children?: TreeDataNode[];
isLeaf?: boolean;
}
interface TransferComSelectProps {
loadDataFetch: (params: { parentId: string }) => Promise<any>;
treeData?: TreeDataNode[];
type?: number;
selectedData?: {id:string}[];
handleChange?: (data: { selectedIds: string[]; type: number }) => void;
className?: string;
style?: React.CSSProperties;
placeholder?: string; // 新增:自定义 placeholder
switchText?: { onlyThisLevel: string