当页面滚动时,判断某组件是否在屏幕中显示
实现功能:通过嵌套该组件,当被嵌套组件显示在页面时,通过
PubSub
消息订阅传递给父组件
- 封装组件
import { useEffect, useRef } from 'react'
import PubSub from 'pubsub-js' // 消息订阅
/**
* 检查当前组件是否在屏幕
* id -> 当前组件显示在屏幕时,通过消息订阅发送出去
* @param {*} props {id:'组件唯一键'}
* @returns 组件
*/
const Module = props => {
const dom = useRef()
const { id } = props
const height = document.body.clientHeight // 获取屏幕高度
const bindHandleScroll = () => {
const top = dom.current.getBoundingClientRect().top
if (top >= 0 && top <= height) {
PubSub.publish('window-show-module-code', id)
}
}
useEffect(() => {
// 页面滚动监听
window.addEventListener('scroll', bindHandleScroll)
return () => {
// 注销页面滚动监听
window.removeEventListener('scroll', bindHandleScroll)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
return <div ref={dom}>{props.children}</div>
}
export default Module
- 父组件
import { useEffect } from 'react'
import PubSub from 'pubsub-js' // 消息订阅
import WindowScroll from '../../../components/WindowScroll'
const Centre = () => {
/**
* 生命周期-组件挂载
* 订阅-当前显示组件,并高亮该组件
*/
useEffect(() => {
PubSub.subscribe('window-show-module-code', (_, id) => {
console.log('传入的ID', id)
})
}, []) // eslint-disable-line react-hooks/exhaustive-deps
return (
<>
{list.map(e => {
return (
<WindowScroll key={e.key} id={e.path}>
<ModuleCode {...e} />
</WindowScroll>
)
})}
</>
)
}