使用带反应路由器的锚点

Don*_*n P 32 javascript react-router

如何使用react-router,并将链接导航到特定页面上的特定位置?(例如/home-page#section-three)

细节:

我正在使用react-router我的React应用程序.

我有一个站点范围的导航栏,需要链接到页面的特定部分,如/home-page#section-three.

因此,即使您在说/blog,单击此链接仍将加载主页,第三部分滚动到视图中.这正是标准的<a href="/home-page#section-three>运作方式.

注意:react-router的创建者没有给出明确的答案.他们说它正在进行中,并且同时使用其他人的答案.我会尽力保持这个问题的最新进展和可能的解决方案,直到出现主导的问题.

研究:


如何使用反应路由器的普通锚链接

这个问题是从2015年(所以10年前的反应时间).最受欢迎的答案是用来HistoryLocation代替HashLocation.基本上这意味着将位置存储在窗口历史记录中,而不是存储在哈希片段中.

坏消息是......即使使用HistoryLocation(大多数教程和文档在2016年所说的内容),锚标签仍然不起作用.


https://github.com/ReactTraining/react-router/issues/394

ReactTraining上的一个线程,关于如何使用anchor链接与react-router.这是没有确认的答案.要小心,因为大多数建议的答案都已过时(例如使用"哈希"道具<Link>)


mal*_*r53 22

React Router Hash Link为我工作.易于安装和实施:

$ npm install --save react-router-hash-link
Run Code Online (Sandbox Code Playgroud)

在component.js中将其导入为Link:

import { HashLink as Link } from 'react-router-hash-link';
Run Code Online (Sandbox Code Playgroud)

而不是使用锚<a>,使用<Link> :

<Link to="home-page#section-three">Section three</Link>
Run Code Online (Sandbox Code Playgroud)

注意:我使用HashRouter而不是Router:

  • 该解决方案无法以编程方式推送历史记录。 (2认同)

Don*_*n P 21

这是我找到的一个解决方案(2016年10月).它是跨浏览器兼容的(在ie,ff,chrome,mobile safari,safari中测试).

您可以为onUpdate路由器提供属性.只要路由更新,就会调用此方法.此解决方案使用onUpdate属性检查是否存在与哈希匹配的DOM元素,然后在路由转换完成后滚动到该元素.

您必须使用browserHistory而不是hashHistory.

在这个帖子中,答案是"Rafrax" .

将此代码添加到您定义的位置<Router>:

import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';

const routes = (
  // your routes
);

function hashLinkScroll() {
  const { hash } = window.location;
  if (hash !== '') {
    // Push onto callback queue so it runs after the DOM is updated,
    // this is required when navigating from a different page so that
    // the element is rendered on the page before trying to getElementById.
    setTimeout(() => {
      const id = hash.replace('#', '');
      const element = document.getElementById(id);
      if (element) element.scrollIntoView();
    }, 0);
  }
}

render(
  <Router
    history={browserHistory}
    routes={routes}
    onUpdate={hashLinkScroll}
  />,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)

如果您感觉懒惰并且不想复制该代码,则可以使用仅为您定义该功能的Anchorate.https://github.com/adjohnson916/anchorate

  • 只是想提一下,这个解决方案将不再适用于`react-router`的第4版,`onUpdate`方法已被删除. (3认同)
  • 刚刚发布了一个针对 `react-router` V4 的解决方案,见下文。 (2认同)

Mat*_*tta 21

这是一个不需要任何订阅或第三方软件包的简单解决方案。它应该与react-router@3和一起使用和react-router-dom

工作示例https : //fglet.codesandbox.io/

来源(不幸的是,它目前在编辑器中不起作用):

编辑简单的 React 锚点


#ScrollHandler 钩子示例

import { useEffect } from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";

const ScrollHandler = ({ location, children }) => {
  useEffect(
    () => {
      const element = document.getElementById(location.hash.replace("#", ""));

      setTimeout(() => {
        window.scrollTo({
          behavior: element ? "smooth" : "auto",
          top: element ? element.offsetTop : 0
        });
      }, 100);
    }, [location]);
  );

  return children;
};

ScrollHandler.propTypes = {
  children: PropTypes.node.isRequired,
  location: PropTypes.shape({
    hash: PropTypes.string,
  }).isRequired
};

export default withRouter(ScrollHandler);
Run Code Online (Sandbox Code Playgroud)

#ScrollHandler 类示例

import { PureComponent } from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";

class ScrollHandler extends PureComponent {
  componentDidMount = () => this.handleScroll();

  componentDidUpdate = prevProps => {
    const { location: { pathname, hash } } = this.props;
    if (
      pathname !== prevProps.location.pathname ||
      hash !== prevProps.location.hash
    ) {
      this.handleScroll();
    }
  };

  handleScroll = () => {
    const { location: { hash } } = this.props;
    const element = document.getElementById(hash.replace("#", ""));

    setTimeout(() => {
      window.scrollTo({
        behavior: element ? "smooth" : "auto",
        top: element ? element.offsetTop : 0
      });
    }, 100);
  };

  render = () => this.props.children;
};

ScrollHandler.propTypes = {
  children: PropTypes.node.isRequired,
  location: PropTypes.shape({
    hash: PropTypes.string,
    pathname: PropTypes.string,
  })
};

export default withRouter(ScrollHandler);
Run Code Online (Sandbox Code Playgroud)

  • 很不幸的是,不行。某些浏览器(如 Safari)不会立即更新滚动位置。 (2认同)

rit*_*njn 12

此解决方案适用于 react-router v5

import React, { useEffect } from 'react'
import { Route, Switch, useLocation } from 'react-router-dom'

export default function App() {
  const { pathname, hash } = useLocation();

  useEffect(() => {
    // if not a hash link, scroll to top
    if (hash === '') {
      window.scrollTo(0, 0);
    }
    // else scroll to id
    else {
      setTimeout(() => {
        const id = hash.replace('#', '');
        const element = document.getElementById(id);
        if (element) {
          element.scrollIntoView();
        }
      }, 0);
    }
  }, [pathname]); // do this on route change

  return (
      <Switch>
        <Route exact path="/" component={Home} />
        .
        .
      </Switch>
  )
}
Run Code Online (Sandbox Code Playgroud)

在组件中

<Link to="/#home"> Home </Link>
Run Code Online (Sandbox Code Playgroud)


ale*_*511 10

只是避免使用 react-router 进行本地滚动:

document.getElementById('myElementSomewhere').scrollIntoView() 
Run Code Online (Sandbox Code Playgroud)

  • 理想情况下,本地滚动会通过路由器,因为这样您就可以从外部链接到文档的特定部分,但是这个答案仍然非常感谢,因为它告诉我需要在 this.props.history.listen 回调中放入哪些代码. (2认同)

ran*_*mor 7

这个问题唐普的回答有时会与ID的元素仍然被渲染或装载,如果该节取决于一些异步操作。以下函数将尝试通过 id 查找元素并导航到该元素并每 100 毫秒重试一次,直到达到最多 50 次重试:

scrollToLocation = () => {
  const { hash } = window.location;
  if (hash !== '') {
    let retries = 0;
    const id = hash.replace('#', '');
    const scroll = () => {
      retries += 0;
      if (retries > 50) return;
      const element = document.getElementById(id);
      if (element) {
        setTimeout(() => element.scrollIntoView(), 0);
      } else {
        setTimeout(scroll, 100);
      }
    };
    scroll();
  }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*len 5

我将Don P 的解决方案(见上文)改编为react-router4(2019 年 1 月),因为不再有任何onUpdate道具<Router>

import React from 'react';
import * as ReactDOM from 'react-dom';
import { Router, Route } from 'react-router';
import { createBrowserHistory } from 'history';

const browserHistory = createBrowserHistory();

browserHistory.listen(location => {
    const { hash } = location;
    if (hash !== '') {
        // Push onto callback queue so it runs after the DOM is updated,
        // this is required when navigating from a different page so that
        // the element is rendered on the page before trying to getElementById.
        setTimeout(
            () => {
                const id = hash.replace('#', '');
                const element = document.getElementById(id);
                if (element) {
                    element.scrollIntoView();
                }
            },
            0
        );
    }
});

ReactDOM.render(
  <Router history={browserHistory}>
      // insert your routes here...
  />,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)


Noa*_*Noa 5

<Link to='/homepage#faq-1'>Question 1</Link>
Run Code Online (Sandbox Code Playgroud)
useEffect(() => {
    const hash = props.history.location.hash
    if (hash && document.getElementById(hash.substr(1))) {
        // Check if there is a hash and if an element with that id exists
        document.getElementById(hash.substr(1)).scrollIntoView({behavior: "smooth"})
    }
}, [props.history.location.hash]) // Fires when component mounts and every time hash changes
Run Code Online (Sandbox Code Playgroud)