這是一個用純函數(shù)組件實現(xiàn)的 lazy-load image
LazyLoad.jsx
import React from 'react'
const css = {
box: {
height: '400px',
border: '1px solid pink',
overflowY: 'scroll',
},
imageBox: {
width: '500px',
height: '500px',
margin: '20px auto',
},
}
const images = [] // 要加載的 img 圖片(jsx)
const refs = [] // 圖片的 ref(操作dom時用)
for (let i=0; i<4; i++) { // 添加4張待加載的圖片
const ref = React.createRef() // 新建空 ref
refs.push(ref) // 放入 ref 數(shù)組
images.push( // 新建 img jsx 放入 images (圖片地址不放入 src 而是放入 自定義屬性 data-src)
<div style={css.imageBox} key={i}>
<img ref={ ref } data-src={`https://pschina.github.io/src/assets/images/${i}.jpg`} />
</div>
)
}
const threshold = [0.01] // 這是觸發(fā)時機(jī) 0.01代表出現(xiàn) 1%的面積出現(xiàn)在可視區(qū)觸發(fā)一次回掉函數(shù) threshold = [0, 0.25, 0.5, 0.75] 表示分別在0% 25% 50% 75% 時觸發(fā)回掉函數(shù)
// 利用 IntersectionObserver 監(jiān)聽元素是否出現(xiàn)在視口
const io = new IntersectionObserver((entries)=>{ // 觀察者
entries.forEach((item)=>{ // entries 是被監(jiān)聽的元素集合它是一個數(shù)組
if (item.intersectionRatio <= 0 ) return // intersectionRatio 是可見度 如果當(dāng)前元素不可見就結(jié)束該函數(shù)。
const {target} = item
target.src = target.dataset.src // 將 h5 自定義屬性賦值給 src (進(jìn)入可見區(qū)則加載圖片)
})
}, {
threshold, // 添加觸發(fā)時機(jī)數(shù)組
});
// onload 函數(shù)
const onload = ()=>{
refs.forEach( (item) => {
io.observe(item.current) // 添加需要被觀察的元素。
} )
}
// 定義懶加載純函數(shù)組件
// 為了監(jiān)聽頁面加載完畢 定義了一個img 利用 onerror 函數(shù)替代 onlaod {src需填寫一個不存在圖片的路徑}
const LazyLoadPage = ()=>(
<div style={css.box}>
{images}
<img onError={onload} src="" />
</div>
)
export default LazyLoadPage

react-lazyload.gif
(完)