在AntDesignPro中的ProFormSelect组件中加入滚动加载及模糊搜索

ProComponents组件使用

ProFormSelect组件



前言

最近在学习使用Ant Design Pro,在这里将遇到的问题罗列出来,方便后续学习,同样,如果你最近也在使用,希望能帮到你。


一、下拉框组件

ProFormSelect支持滚动选择,如果数据过多,查找可能浪费时间,此时,我们可以使用自带的搜索功能,也可以自定义搜索。

二、使用步骤

页面渲染

 <ProFormSelect
          {...props}
          mode={data.optionType === 1 ? 'single' : 'multiple'}
          fieldProps={{
            showSearch: true,
            maxTagCount: 'responsive',
            virtual: true,
            onPopupScroll: e => handleScroll(e),
            onSearch: handleSearchChange,
            //这里可加入自定义加载动画
            dropdownRender: menu => (
              <>
                {menu}
                {loading && (
                  <div
                    style={{
                      width: '100%',
                      height: '50px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    <Spin />
                  </div>
                )}
              </>
            ),
          }}
          options={dataQue}
        />

数据请求

在这里,主要进行数据分页,也就是滚动加载,在里面有一个加载动画,当请求数据时展示

  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<any>([]);
  const [optionCurrent, setOptionCurrent] = useState(1);
  const [hasMoreData, setHasMoreData] = useState(true);
  const getNextPage = async () => {
    if (!hasMoreData) {
      return;
    }
    try {
      const res = await getApiSetOps({
        setId: data.setId,
        optionCurrent,
        optionPageSize: 10,
      });
      setLoading(true);
      const newData: any = res.data;
      setDataSource((prevData: any) => [...prevData, ...newData]);
      setOptionCurrent(pre => (pre += 1));
      if (newData[0].options.length === 0) {
        setLoading(false);
        setHasMoreData(false);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  //监听滚动条
  const handleScroll = (event: any) => {
    const { scrollTop, scrollHeight, clientHeight } = event.target;
    if (scrollHeight - (scrollTop + clientHeight) < 200) {
      getNextPage();
    }
  };

  useEffect(() => {
    getNextPage();
  }, []);

  let dataQue = [];
  if (dataSource && dataSource.length > 0) {
    dataQue = dataSource.map((item: { options: { content: string; optionId: number }[] }) => {
      const convertedOptions = item.options.map(option => {
        const label = option.content.replace(/^[0-9]+##/, ''); // 删除 '#' 之前内容
        const value = option.optionId;
        return { label, value };
      });
      return { options: convertedOptions };
    });
  }

  //防抖函数(搜索时使用)
  const debounce = (func: { (value: any): void; apply?: any }, delay: number | undefined) => {
    let timerId: string | number | NodeJS.Timeout | undefined;
    return (...args: any) => {
      clearTimeout(timerId);
      timerId = setTimeout(() => {
        // eslint-disable-next-line prefer-spread
        func.apply(null, args);
      }, delay);
    };
  };
  const handleSearchChange = debounce((value: any) => {
    const fn = async () => {
      try {
        const res = await getApiSetOps({ setId: data.setId, optionContent: value });
        if (res.code === 0) {
          const newData = res.data;
          setDataSource((prevData: any) => {
            const filteredData = newData.filter(
              (item: any) => !prevData.some((prevItem: any) => prevItem.optionId === item.optionId),
            );
            return [...prevData, ...filteredData];
          });
        }
      } catch (error) {
        console.log(error);
      }
    };
    fn();
  }, 1000);

总结

以上就是对ProFormSelect在使用过程中遇到的问题总结,如果有帮助,可以点个赞哦。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小童不学前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值