Javascript 在 react-router 4 中使用锚标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48223566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:03:03  来源:igfitidea点击:

Using anchor tags in react-router 4

javascriptreactjsreact-router

提问by S. Schenk

I want the page to scroll down to my anchor tags when a user navigates to it through an anchor link.

当用户通过锚链接导航到页面时,我希望页面向下滚动到我的锚标签。

I'm using react-router 4 and I've defined things as follows:

我正在使用 react-router 4,我已经定义了如下内容:

navbar:

导航栏:

export default (props) => {
  const { 
    updateModal,
    updateRoute,
  } = props
  return(
    <Navbar fluid collapseOnSelect>
      <Nav>
        <NavDropdown eventKey="4" title="Solutions" id="nav-dropdown" noCaret>
          <MenuItem eventKey="4.1">
             <Link to='/solution#ipos'>TESTING ANCHOR</Link>
          </MenuItem>
...

some route:

一些路线:

export default class extends Component {
  constructor() {
    super()
    this.state = {
      isLoading: true
    }
  }
  render() {
    return (
      <Grid className='solutions' fluid>
       <Row className='someClass'>
        <div>
          <h2><a href='ipos' id='ipos'>Ipos morna santos paros</a></h2>
          ...

I can see the hash anchor tag in the url and in my redux store when I click on the anchor link in the navebar, and it indeed navigates to the new route, but it doesn't scroll down to the tag itself.

当我单击导航栏中的锚链接时,我可以在 url 和我的 redux 存储中看到哈希锚标记,并且它确实导航到新路由,但它不会向下滚动到标记本身。

Is it up to me to create the scroll function or how is it supposed to work exactly?

是由我来创建滚动功能还是它应该如何工作?

采纳答案by Akhil P

It is a known issue with react router. (https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)

这是反应路由器的一个已知问题。( https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)

There is a solution as well. https://www.npmjs.com/package/react-router-hash-linkthis package solves the issue.

也有解决办法。https://www.npmjs.com/package/react-router-hash-link这个包解决了这个问题。

You have to use this Hash Linkas the Linklike below.

你必须像下面Hash Link那样使用它Link

import { HashLink as Link } from 'react-router-hash-link';

import { HashLink as Link } from 'react-router-hash-link';

回答by Adriano Campos

To scroll down to your anchor tags, you need to install React Router Hash Link, with:

要向下滚动到您的锚标签,您需要安装 React Router Hash Link,使用:

npm install --save react-router-hash-link

then import Hash Link:

然后导入哈希链接:

import { HashLink as Link } from 'react-router-hash-link';

and then use Hash Link, for example:

然后使用哈希链接,例如:

<Link to="/pathLink#yourAnchorTag">Your link text</Link>

and at the destination component, for example:

在目标组件,例如:

<div id= "yourAnchorTag">
      <p>Linked to here<p>
</div>

回答by Filippo Italiano

If you have only few predictable anchor links, the simpliest way to achieve the normal behaviour is to manually scrollIntoView()of the element if you have the expected anchor tag in the Window.location.href.

如果您只有几个可预测的锚链接,实现正常行为的最简单方法是手动删除scrollIntoView()元素,如果您在Window.location.href.

Here the full explanation.

这里有完整的解释

class Page extends react.Component {
    componentDidMount() {
        if (this.$ref && location.href.includes('#my-ref')) {
            this.$ref.scrollIntoView({
                // optional params
                behaviour: 'smooth',
                block: 'start',
                inline: 'center',
            });
        }
    }

     render() {
        return (
            // This is the div you want to scroll to
            <div ref={ref => {
                this.$ref = ref;
            }}>
                Other content
            </div>
        );
    }
}

Check Element.scrollIntoView()and React refs.

检查Element.scrollIntoView()React refs

回答by DSLuminary

Similar to @filippo, but with React hooks and a little Typescript.

类似于@filippo,但带有 React 钩子和一点 Typescript。

    import React, { Functioncomponent, useEffect, useRef } from 'react';
    import { useLocation } from 'react-router-dom';
    
    const MyFunc: FunctionComponent = () => {
    const myRef = useRef<null | HTMLDivElement>(null);
    
        useEffect(() => { 
    if (myRef && location.hash.includes('#my-ref')) { 
    
    myRef?.current?.scrollIntoView({
    behavior: 'smooth',
    block: 'start',
    inline: 'center'
    });
    
    }
    }, [myRef, location.hash]);
    
    return (
    <div> Some stuff before </div>
    <div ref={myRef}> Scroll to me </div>
    <div> Some stuff after </div>
    )
    
    } 
       
        export default MyFunc;

回答by Puka

You can pass an object to Link, like this

您可以像这样将对象传递给 Link

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

ref. https://reacttraining.com/react-router/web/api/Link

参考 https://reacttraining.com/react-router/web/api/Link

回答by Telework Inc.

I was using Gatsby, and my solution was to use @reach/routerin the form:

我正在使用 Gatsby,我的解决方案是使用@reach/router以下形式:

import { navigate } from '@reach/router';
navigate('#some-link');

Link to Gatsby documentation.

链接到 Gatsby 文档