原生 js 實現瀑布流佈局、React 版本的瀑布流佈局元件

大桔子發表於2022-04-11
  1. 直接cdn引入

    // 示例程式碼: https://github.com/hugeorange/waterfalljs/blob/master/src/index.html
    <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

API

option

選項含義值型別預設值備註
el容器元素idstring#waterfall容器必須是ul元素
columnWidth每一列的寬度number360
columnCount多少列number-不傳會自動分配
gap每列之間的間隙number 500
delay輪詢排布的間隔時間number#waterfall
customStyle自定義樣式string-
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裡面的包

相關文章