GatsbyJS + React 中的锚链接

我已经在这个问题上停留了一段时间了。我在普通的 create-react-app 中创建项目后创建了一个 GatsbyJS 项目。一切正常,直到我对代码进行了一些重大更改。这毁了我的导航 - 但不完全!徽标导航和页脚中的链接仍然有效,但 NavBar 项目无效。我正在使用 gatsby 插件:'gatsby-plugin-anchor-links' ( https://www.gatsbyjs.com/plugins/gatsby-plugin-anchor-links/ )。


这是我的 NavBarItem 代码(组件):


import React from "react"

import "../../Bulma.css"

import { Link } from "gatsby"


function NavBarItem(props) {

  return (

    <Link

      className={"pl-6 pr-6 has-text-black navbar-item " + props.class}

      to={"/#" + props.location}

    >

      {props.text}

    </Link>

  )

}


export default NavBarItem

这是我的 NavBar 组件:


import React from "react"

import NavBarItem from "./assets/NavBarItem"

import "../Bulma.css"

import "./NavBar.css"

import { Link } from "gatsby"

import logo from "../../static/dronarfoton_logo.png"


class NavBar extends React.Component {

  constructor(props) {

    super(props)

    this.state = {

      isActive: true,

    }

  }


  toggle() {

    this.setState({ isActive: !this.state.isActive })

  }


  render() {

    return (

      <nav

        className="navbar has-text-white has-background-grey-lighter has-navbar-fixed-top is-fixed-top"

        role="navigation"

        aria-label="main navigation"

      >

        <div className="navbar-brand">

          <a href="#Top" className="navbar-item">

            <img

              alt="Logga som det står DrönarFoton på. Det visar en drönare och text."

              src={logo}

              width="112"

              height="28"

            />

          </a>


          <a

            role="button"

            className={

              this.state.isActive

                ? "navbar-burger burger"

                : "is-active navbar-burger burger"

            }

            aria-label="menu"

            aria-expanded={this.state.isActive ? "false" : "true"}

            data-target="navbarBasicExample"

            onClick={this.toggle.bind(this)}

同样,“导航栏品牌”链接有效,但导航栏项目无效。


我的想法是它与它的呈现方式有关,但我无法弄清楚这是如何发生的以及为什么会发生。


另一个有趣的部分是,如果我在我的浏览器中禁用 JAVASCRIPT,链接就可以工作


如果有人知道为什么会这样。请告诉我。


谢谢//古斯塔夫


繁星淼淼
浏览 76回答 1
1回答

人到中年有点甜

prop location您在组件中使用 a<NavBarItem>但最后,您呈现的是<Link>, 它不接受散列 ( #) 既不接受锚点行为。<Link>正如您在的 API 文档(应用内导航)中所见:既不能<Link>也navigate不能用于带有散列或查询参数的路线导航。如果您需要这种行为,您应该使用锚标记或导入@reach/router包(Gatsby 已经依赖该包)以使用其导航功能。如果你想在你的 中使用锚链接<NavBarItem>,你应该使用常规<a>或gatsby-plugin-anchor-links正确使用: <AnchorLink     to="/about#team"     title="Check out our team!"     className="stripped"     stripHash   />请记住,使用常规<a>,您将失去 上的所有好处,@reach/routing并且您将完全刷新页面。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript