【问题标题】:Href to another page React GatsbyHref to another page React Gatsby
【发布时间】:2020-03-19 21:48:09
【问题描述】:

我有一个带有以下链接的菜单:

<li className="nav-item" key={link.name}>
 <a href={`page-2#second-section`}>{link.name}</a>
</li>

但是当我点击它时,我会被带到: http://localhost:8000/page-2/#second-section

但仍位于页面顶部,而不是像 id:"second-section" 的 div 所在的页面中间。

当我再次单击它转到该部分时,网址是:

http://localhost:8000/page-2/page-2#second-section

我怎样才能做到这一点?

<div id="first-section">
   <hr></hr>
   <SEO title="Page one" />
</div>
<div id="second-section">
   <hr></hr>
   <SEO title="Page two" />
</div>

当我直接这样做时:

<li className="nav-item" key={link.name}>
    <a href="#second-section">{link.name}</a>
</li>

它在同一页面上工作。但它在其他页面不起作用

【问题讨论】:

  • 你可以试试&lt;a href="/page-2#second-section"&gt;{link.name}&lt;/a&gt; 吗?
  • 不起作用。页面仍然在顶部而不是去那个 div
  • 其实这应该回答你的问题stackoverflow.com/questions/48223566/…
  • 另外你应该使用Link(从gatsby导入)而不是常规的

标签: javascript jquery html reactjs gatsby


【解决方案1】:

对于这种用途,我们必须使用 Anchorlinks 更多详情请点击此处https://www.gatsbyjs.org/packages/gatsby-plugin-anchor-links/

import { AnchorLink } from "gatsby-plugin-anchor-links";

export default () => (
  <AnchorLink to="/about#team" title="Our team">
    <span>Check out our team!</span>
  </AnchorLink>
);
// => <a href="/about#team" title="Our team"><span>Check out our team!</span></a>

export default () => (
  <AnchorLink to="/about#team" title="Check out our team!" />
);
// => <a href="/about#team" title="Check out our team!">Check out our team!</a>

export default () => (
  <AnchorLink
    to="/about#team"
    title="Check out our team!"
    className="stripped"
    stripHash
  />
);
// => <a href="/about" class="stripped" title="Check out our team!">Check out our team!</a>
// => Hash will be stripped, and a full page scroll will occure onRouteChange

export default () => <AnchorLink to="/about" title="About us" />;
// => <a href="/about" title="About us">About us</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 2019-06-27
    • 1970-01-01
    • 2016-09-10
    • 2021-11-13
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多