React路由器向下滚动新页面

时间:2016-06-20 19:13:35

标签: javascript reactjs redux react-router

我使用react-router ^2.4.1遇到了一个问题,如果我向下滚动主页,然后转到新页面,它也会向下滚动,而不是在顶部(预期的行为)。< / p>

我正在使用这个入门包:react-webpack-node而我的routes.jsx看起来像这样

import React from 'react'
import { Route, IndexRoute } from 'react-router'
import cookie from 'react-cookie'

import App from 'containers/App'
import HomePage from 'containers/HomePage'
import WaitingListPage from 'containers/WaitingListPage'
import NotFoundPage from 'containers/NotFoundPage'
import SupportPage from 'containers/SupportPage'

/*
 * @param {Redux Store}
 * We require store as an argument here because we wish to get
 * state from the store after it has been authenticated.
 */
export default (store) => {
  const hasQueueToken = (nextState, replace, callback) => {
    if (cookie.load('queueToken')) {
      replace({
        pathname: `/waiting-list/${cookie.load('queueToken')}`,
        state: { nextPathname: nextState.location.pathname }
      })
    }
    callback()
  }

  return (
    <Route path='/' component={App}>
      <IndexRoute component={HomePage} />
      <Route path='/w_ref/:ref' component={HomePage} />
      <Route path='/waiting-list/:token' component={WaitingListPage} />
      <Route path='/waiting-list' onEnter={hasQueueToken} component={WaitingListPage} />
      <Route path='/support' component={SupportPage} />
      <Route path='/terms-and-conditions' component={TermsConditions} />
      <Route path='/privacy-policy' component={PrivacyPolicy} />
      <Route path='*' component={NotFoundPage} />
    </Route>
  )
}

2 个答案:

答案 0 :(得分:4)

React Router不包含从2.0.0版本开始的滚动状态管理。

推荐的方法是使用scroll-behavior react-router-scroll装饰路由器,如in this example所示:

import { applyRouterMiddleware, browserHistory, Router } from 'react-router';
import useScroll from 'react-router-scroll';

/* ... */

ReactDOM.render(
  <Router
    history={browserHistory}
    routes={routes}
    render={applyRouterMiddleware(useScroll())}
  />,
  container
);

答案 1 :(得分:0)

@John Trichereau

滚动到底部可以通过回复useScroll来完成,你的回调看起来像:

function customScroll (prevRouterProps, location) {
  // on route /foo scroll to bottom
  if (location.pathname == '/foo') return 'fooBottomDiv';
  // on all other routes, follow useScroll default behavior
  return prevRouterProps && location.pathname !== prevRouterProps.location.pathname;
}

你可以将它传递给你的路由器:

<Router render={ applyRouterMiddleware(useScroll((prevRouterProps, { location }) => customScroll(prevRouterProps, location))) }>

在您的页面中,您需要插入一个ID为fooBottomDiv的隐形div。如果您不想插入此类div,则可以customScroll返回一个2元素数组[x, y],可以[0, Number.MAX_SAFE_INTEGER]滚动到底部。

文档here

但是请注意,如果您的页面有一个加载数据并显示它的组件,那么它很可能不起作用,因为customScroll函数仅在路由匹配时被调用,而您的数据可能是异步调用的并且在之后被接收路线匹配。 在这种情况下,使用起来最方便

ReactDOM.findDOMNode(this.refs.fooBottomDiv).scrollIntoView({ behavior: 'smooth' });

在React生命周期方法componentDidMountcomponentDidUpdate中,您的组件将包含ref属性ref='fooBottomDiv的空div。

相关问题