原生 js 实现瀑布流布局、React 版本的瀑布流布局组件

1,954 阅读2分钟

使用方式

  1. 直接cdn引入
    // 示例代码: https://github.com/hugeorange/waterfalljs/blob/master/src/index.html
    // 容器
    <ul id="waterfall"></ul>
    <script src="https://unpkg.com/browse/waterfalljs-layout@latest/dist/waterfalljs-layout.esm.js"></script>
    <script>
        const wf = new Waterfall({
            el: '#waterfall',
            columnWidth: 236,
            gap: 24,
            delay: 800,
            // 自定义样式按需使用
            customStyle: ''
        })
        // ..................................
        // 初始化数据或加载更多场景时时调用 
        wf.loadMore()
    
  2. React 版本
    // yarn add waterfalljs-layout
    import Waterfall from "waterfalljs-layout/react";
    // 详细演示页面请参考 https://codesandbox.io/s/busy-faraday-w538tc
    <Waterfall
        columnWidth={236}
        columnCount={2}
        gap={24}
        customStyle={customStyle}
        onChangeUlMaxH={(h) => console.log('ul容器高度-->', h)}
      >
        {images.map((item, index) => {
          return (
            <li key={index} >
              <div><img src={item} alt="" /></div>
            </li>
          );
        })}
      </Waterfall>
    
  3. 简单粗暴的办法直接拷贝src/index.ts目录下的代码到你的项目中使用,vue、react项目均可,或是直接 esmodule 导入 import Waterfall from "waterfalljs-layout,具体使用方式同 1

API

option

选项含义值类型默认值备注
el容器元素idstring#waterfall容器必须是ul元素,使用react组件不必传此此项
columnWidth每一列的宽度number360
columnCount多少列number-不传会自动分配
gap每列之间的间隙number
delay轮询排布的间隔时间number500
customStyle自定义样式string-即普通css样式的模板字符串
onChangeUlMaxH实时获取容器高度(h: number) => void-可在上拉加载场景中使用

rollup 打包遇到的问题

  • 采用 rollup 多入口打包,分别打出无框架依赖的核心 js 库,和 react 版本的库 - 配置文件详见 rollup.config.js,react 版本本地开发调试配置文件rollup.config.react-dev.js
  • 为了方便 核心 js库 引用及 react 版本没有区分目录,统一放在 src 根目录下,ts 自动生成 .d.ts 会根据文件名自动生成一个目录(并且会为所有文件生成 .d.ts) 如下图所示 dts.png
  • package.json 怎么定义导出两个包,参考自 swiper 的定义方式 Node.JS(新)Package.json exports 字段
  • swiper 定义方式 package-json-export.png
  • TODO: rollup react开发环境无法加载node_module里面的包