Next.js项目中isotope-layout按日期排序功能的配置问题咨询
Next.js中Isotope布局日期排序问题修复
核心修改逻辑
你当前代码中getSortData的date字段直接绑定了CSS选择器,Isotope默认会提取对应元素的文本字符串按字典序排序,因此无法按真实时间先后排序,只需将date字段改为返回时间戳的解析函数即可。
注意:如果你项目中没有引入jQuery,不要使用jQuery风格的DOM方法,改用原生DOM操作即可。
如果需要日期从新到旧降序排列,可在初始化配置或调用arrange方法时添加排序方向配置:
sortAscending: { date: false // date字段降序排列 }
修改后的完整代码
const KeyOutcomes = (props) => { const isotope = useRef() const [sortKey, setSortKey] = useState('date') // 初始化Isotope实例并传入配置 useEffect(() => { isotope.current = new Isotope('.news', { itemSelector: '.newsInner', layoutMode: 'fitRows', getSortData: { header: '.header', // 修改为日期解析函数,返回时间戳用于数值排序 date: function(itemElem) { const dateText = itemElem.querySelector('.date').textContent // 适配你当前的dd/mm/yyyy日期格式,避免浏览器解析兼容问题 const [day, month, year] = dateText.split('/') return Date.parse(`${year}/${month}/${day}`) } }, // 可选:配置日期默认降序排列 sortAscending: { date: false } }) // 组件销毁时清理实例 return () => isotope.current.destroy() }, []) // 监听排序关键词变化重新排布元素 useEffect(() => { isotope.current.arrange({ sortBy: `${sortKey}` }) }, [sortKey]) const handleSortKeyChange = (key) => () => setSortKey(key) return ( <div className="container"> <div className="row"> <div className="col-12"> <div className="sortAndFilter"> <ul className="sortFilter"> <li>排序方式:</li> <li onClick={handleSortKeyChange('header')} > 标题 </li> <li onClick={handleSortKeyChange('date')} > 日期 </li> </ul> </div> <div className="news"> <div className="newsInner vege"> <div className="newsText two"> <h3 className="header">V类新闻标题</h3> <p className="date">02/05/2020</p> </div> </div> <div className="newsInner one"> <div className="newsText"> <h3 className="header">D类新闻标题</h3> <p className="date">26/05/2020</p> </div> </div> <div className="newsInner one"> <div className="newsText"> <h3 className="header">G类新闻标题</h3> <p className="date">10/12/2021</p> </div> </div> </div> </div> </div> </div> ) }
内容的提问来源于stack exchange,提问作者MomasVII
相关产品推荐
相关产品推荐

