You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React(Typescript)的isotope-layout中获取筛选后的元素数量

Isotope 筛选后元素数量获取方案

你可以直接调用Isotope实例内置的getFilteredItemElements()方法获取所有匹配筛选条件的元素数组,取数组长度即可得到目标数量,以下是两种适配你现有代码的实现方式:

方案1:调用arrange后直接获取(适合无复杂动画的场景)

在你执行arrange筛选的代码后直接调用API取值即可,修改你的onFilterChange方法:

const onFilterChange = (val : Types.SelectedFilterValue ) => {          
   var _str =  val.filterValue.map( x => ('(\\|' + x + '\\|)')).join('|');

   var filterFns = { 
      //match
      matches: function(itemelement : Element) {
        if(itemelement != null) {
          try{
            var strTarget : string  = itemelement.getAttribute('data-' + val.filterType.toLowerCase()) ?? '';  
             return strTarget.match(new RegExp(_str, "i"));
          }catch(e) {
            console.log(e);
          }
        }     
      },  
  };

  // use matching filter function
  let pattern : any = filterFns['matches']  || '*';    
  isotope.current?.arrange({ filter: pattern });   

  // 新增:获取筛选后数量
  const filteredCount = isotope.current?.getFilteredItemElements().length ?? 0;
  // 可以赋值给state用于页面展示
  setFilteredCount(filteredCount);
 };

方案2:监听arrangeComplete事件取值(更稳妥,适配有动画/异步布局的场景)

如果你的Isotope布局有过渡动画,建议监听布局完成事件后取值,避免拿到未更新的旧数据,修改初始化的useEffect代码:

// 先导入Isotope类型(如果TS报类型错误的话)
import type Isotope from 'isotope-layout';

// 组件内可以定义state存储数量
const [filteredCount, setFilteredCount] = useState<number>(0);

useEffect(() => {  
    isotope.current = new Isotope(".iso-filter-container", {
      itemSelector: ".iso-filter-item",
      masonry: {
        columnWidth: 50,  
        gutter: 12        
      } ,   
    });   

    // 绑定布局完成事件,每次筛选、排序、重排完成后都会触发
    const handleArrangeDone = () => {
      const count = (isotope.current as Isotope)?.getFilteredItemElements().length ?? 0;
      setFilteredCount(count);
    }
    isotope.current.on('arrangeComplete', handleArrangeDone);

    // cleanup
     return () => {
        isotope.current?.off('arrangeComplete', handleArrangeDone);
        isotope.current?.destroy();
     };
  }, [fullcatalog]); 

如果遇到TS类型提示错误,给isotope实例加上as Isotope类型断言即可解决。

内容的提问来源于stack exchange,提问作者moonk2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:54:02