首先我们先写返回顶部的样式
然后绑定一个点击事件,滚动到顶部
BackTop onClick={this.props.toTop}>返回</BackTop>
toTop(){
console.log(111)
window.scrollTo(0,0)
}
这样就可以实现点击返回到顶部了。
接下来我们要写滚动到一定距离出现,那么我们就需要在reducer.js中定义一个默认数据
showTop:false
在index.js中使用mapStateToProps接受这个值,并且使用三元运算通过控制showTop的值来控制显示隐藏
const mapStateToProps = (state) =>{
return {
showTop:state.components.get('showTop')
}
}
//通过三元控制显示隐藏
{
this.props.showTop ? <BackTop onClick={this.props.toTop}>返回</BackTop> : null
}
这时候就需要去监听,页面滚动的距离,直到页面滚动到一定距离时,派发action给store,最后改变reducer中的数据,从而达到目的
//在componentDidMount中监听事件
componentDidMount() {
this.bindEvents();
}
//然后监听
bindEvents() {
window.addEventListener("scroll", this.props.changeScrollTop)
}
//在mapDispatch中将数据传递给store,并且判断滚动到什么地方派发
const mapDispatchToProps = (dispatch) =>{
return{
changeScrollTop() {
if(document.documentElement.scrollTop > 400){
dispatch(actionCreators.changeScrollShow(true))
}else {
dispatch(actionCreators.changeScrollShow(false))
}
}
}
}
在actionCreators定义changeScrollShow方法
export const changeScrollShow = (show) => ({
type:actionTypes.CHANGE_SCROLL_SHOW,
show
})
最后在reducer中定义就可以啦
if(action.type === actionTypes.CHANGE_SCROLL_SHOW){
return state.set('showTop',action.show)
}