本文为小伙伴们讲解的是关于React封装CustomSelect组件教程,感兴趣的小伙伴一起来看看吧。
由于考虑组件拆分得比较细,层级比较多,为了方便使用了React.createContext + useContext作为参数向下传递的方式。
首先需要知道antd的Popover组件是继承自Tooltip组件的,而我们的CustomSelect组件是继承自Popover组件的。对于这种基于某个组件的二次封装,其props类型一般有两种方式处理: 继承, 合并。
interface IProps extends XXX; type IProps = Omit& {...};
对于Popover有个很重要的触发类型: trigger,默认有四种"hover" "focus" "click" "contextMenu", 并且可以使用数组设置多个触发行为。但是我们的需求只需要"hover"和"click", 所以需要对该字段进行覆盖。
对于Select, Checkbox这种表单控件来说,对齐二次封装,很多时候需要进行采用'受控组件'的方案,通过'value' + 'onChange'的方式"接管"其数据的输入和输出。并且value不是必传的,使用组件时可以单纯的只获取操作的数据,传入value更多是做的一个初始值。而onChange是数据的唯一出口,我觉得应该是必传的,不然你怎么获取的到操作的数据呢?对吧。
有一个注意点: 既然表单控件时单选框,复选框, 那我们的输入一边是string, 一边是string[],既大大增加了编码的复杂度,也增加了使用的心智成本。所以我这里的想法是统一使用string[], 而再单选的交互就是用value[0]等方式完成单选值与数组的转换。
// types.ts import type { TooltipProps } from 'antd'; interface OptItem { id: string; name: string; disabled: boolean; // 是否不可选 children?: OptItem[]; // 递归嵌套 } // 组件调用的props传参 export type IProps = Omit& { /** 选项类型: 单选, 复选 */ type: 'radio' | 'checkbox'; /** 选项列表 */ options: OptItem[]; /** 展示文本 */ placeholder?: string; /** 触发行为 */ trigger?: 'click' | 'hover'; /** 受控组件: value + onChange 组合 */ value?: string[]; onChange?: (v: string[]) => void; /** 样式间隔 */ size?: number; }
import type { Dispatch, MutableRefObj, SetStateAction } from 'react'; import { createContext } from 'react'; import type { IProps } from './types'; export const Ctx = createContext<{ options: IProps['options']; size?: number; type: IProps['type']; onChange?: IProps['onChange']; value?: IProps['value']; // 这里有两个额外的状态: shadowValue表示内部的数据状态 shadowValue: string[]; setShadowValue?: Dispatch>; // 操作弹出框 setVisible?: (value: boolean) => void; // 复选框的引用, 暴露内部的reset方法 checkboxRef?: MutableRefObject<{ reset: () => void; } | null>; }>({ options: [], shadowValue: [], type: 'radio' });
// index.tsx /** * 自定义下拉选择框, 包括单选, 多选。 */ import { FilterOutlined } from '@ant-design/icons'; import { useBoolean } from 'ahooks'; import { Popover } from 'antd'; import classnames from 'classnames'; import { cloneDeep } from 'lodash'; import type { FC, ReactElement } from 'react'; import { memo, useEffect, useRef, useState } from 'react'; import { Ctx } from './config'; import Controls from './Controls'; import DispatchRender from './DispatchRender'; import Styles from './index.less'; import type { IProps } from './types'; const Index: FC= ({ type, options, placeholder = '筛选文本', trigger = 'click', value, onChange, size = 6, style, className, ...rest }): ReactElement => { // 弹窗显示控制(受控组件) const [visible, { set: setVisible }] = useBoolean(false); // checkbox专用, 用于获取暴露的reset方法 const checkboxRef = useRef<{ reset: () => void } | null>(null); // 内部维护的value, 不对外暴露. 统一为数组形式 const [shadowValue, setShadowValue] = useState ([]); // value同步到中间状态 useEffect(() => { if (value && value?.length) { setShadowValue(cloneDeep(value)); } else { setShadowValue([]); } }, [value]); return ( ); }; const CustomSelect = memo(Index); export { CustomSelect }; export type { IProps }; { setVisible(vis); // 这里是理解难点: 如果通过点击空白处关闭了弹出框, 而不是点击确定关闭, 需要额外触发onChange, 更新数据。 if (vis === false && onChange) { onChange(shadowValue); } }} placement="bottom" trigger={trigger} content={ {/* 分发自定义的子组件内容 */}} {...rest} > {placeholder ?? '筛选文本'}{/* 控制行 */}
/** 控制按钮行: "重置", "确定" */ import { Button } from 'antd'; import { cloneDeep } from 'lodash'; import type { FC } from 'react'; import { useContext } from 'react'; import { Ctx } from './config'; import Styles from './index.less'; const Index: FC = () => { const { onChange, shadowValue, setShadowValue, checkboxRef, setVisible, value, type } = useContext(Ctx); return (); }; export default Index;
/** 分发详情的组件,保留其可拓展性 */ import type { FC, ReactElement } from 'react'; import CheckboxRender from './CheckboxRender'; import RadioRender from './RadioRender'; import type { IProps } from './types'; const Index: FC<{ type: IProps['type'] }> = ({ type }): ReactElement => { let res: ReactElement = <>>; switch (type) { case 'radio': res =; break; case 'checkbox': res = ; break; default: // never作用于分支的完整性检查 ((t) => { throw new Error(`Unexpected type: ${t}!`); })(type); } return res; }; export default Index;
import { Radio, Space } from 'antd'; import type { FC, ReactElement } from 'react'; import { memo, useContext } from 'react'; import { Ctx } from './config'; const Index: FC = (): ReactElement => { const { size, options, shadowValue, setShadowValue } = useContext(Ctx); return ({ // 更新数据 if (target.value) { setShadowValue?.([target.value]); } else { setShadowValue?.([]); } }} > ); }; export default memo(Index);{options?.map((item) => ( {item.name} ))}
个人总结
以上就是关于React封装CustomSelect组件教程的全部内容了,感兴趣的小伙伴记得点击关注哦。