现在web页面要兼容各种设备,部分页面的内容长度在手机端就显得过于冗长。除了给客户提供一个按钮,一键返回顶部。更好的客户体验就是当客户做某种操作的时候,就自动滚动到顶端。这样就能顺畅的进行接下来的操作了。
目前我所接触到需要自动返回顶部的需求分为两种
- 当客户切换页面时
- 当客户当前页面进行某些操作或者顶端显示错误信息
总共两个步骤
1.创建一个单独的组件
import { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { ACTION_ONE, ACTION_TWO } from '../actions/actionTypes';
class ScrollToTop extends Component {
componentDidMount () {
const store = this.props.store;
/**
* @function 匿名函数: 通过store.subscribe监听最新的action,如果类型符合,就执行返回顶部
*
* */
store.subscribe(() => {
const actionType = store.getState().lastAction.type;
switch (actionType) {
case ACTION_ONE:
case ACTION_TWO:
window.scrollTo(0, 0);
break;
default: break;
}
});
}
componentDidUpdate (prevProps) {
/**
* 当route路径发生变化的时候,执行返回顶部
* */
if (this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0);
}
}
render () {
return null;
}
}
export default withRouter(ScrollToTop);
- 在根文件上引用这个组件(index.js / app.js)
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import configureStore from '../../store/configureStore';
import Reducer from './reducers';
import {Route, Switch, HashRouter as Router, Redirect} from 'react-router-dom';
import Home from './pages/Home';
import View from './pages/View';
import ScrollToTop from './components/ScrollToTop';
import initialState from './initialState';
const store = configureStore(initialState, Reducer);
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<ScrollToTop store={store} />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/view' component={View} />
</Switch>
</div>
</Router>
</Provider>,
document.getElementById('app')
);
还是很简单吧。把公用方法用一个组件包起来,也便于以后的升级扩展。任何有关返回顶部的操作,只需要把action type添加进去就可以了。
感谢观看,如果有什么疑问,欢迎留言~~ 比心!!