Skip to content

Commit

Permalink
fix: 解决 Sticky 组件的若干问题
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Mar 18, 2019
1 parent 4a1a2cf commit 25d7c4a
Showing 1 changed file with 35 additions and 23 deletions.
58 changes: 35 additions & 23 deletions src/components/Sticky/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ class MSticky extends component({
index: number = 0

componentWillMount() {
this.index = stickyComponents.length
stickyComponents.push(this)
this.index = stickyComponents.length - 1
this.disposer.add(() => {
stickyComponents.splice(this.index, 1)
stickyComponents.splice(
stickyComponents.indexOf(this),
1,
)
})
}

Expand All @@ -37,31 +40,40 @@ class MSticky extends component({
wx.createSelectorQuery()
.in(this.$scope)
.select('.m-sticky')
.boundingClientRect(res => {
.boundingClientRect(({ height }) => {
this.setState({
contentHeight: res.height,
contentHeight: height,
})

// 监听吸顶内容的位置
const top = -(this.index === 0 ? 0 : height)
const intersectionObserver = wx.createIntersectionObserver(this.$scope)
const relativeToViewport = intersectionObserver.relativeToViewport({ top }) as any
relativeToViewport.observe(
'.m-sticky',
(res: wx.ObserveCallbackResult) => {
const fixed = res.intersectionRatio <= 0 && res.boundingClientRect.top < -top

this.setState({ fixed })

// 切换前一个吸顶组件的状态
if (this.index >= 1) {
const prevSticky = stickyComponents[this.index - 1]
if (prevSticky.state.fixed !== fixed) {
prevSticky.setState({
fixed: !fixed,
})
}
}
},
)

// 处置收集
this.disposer.add(
() => intersectionObserver.disconnect(),
)
})
.exec()
// 监听吸顶内容的位置
const intersectionObserver = wx.createIntersectionObserver(this.$scope)
const relativeToViewport = intersectionObserver.relativeToViewport({ top: 0 }) as any
relativeToViewport.observe(
'.m-sticky',
(res: wx.ObserveCallbackResult) => {
const fixed = res.intersectionRatio <= 0 && res.boundingClientRect.top < 0
this.setState({ fixed })
// 切换前一个吸顶组件的状态
if (this.index >= 1) {
stickyComponents[this.index - 1].setState({
fixed: !fixed,
})
}
},
)
this.disposer.add(
() => intersectionObserver.disconnect(),
)
})
}

Expand Down

0 comments on commit 25d7c4a

Please sign in to comment.