如何在 React 中链接到另一个页面?

问题描述 投票:0回答:5

我正在尝试做的事情:我正在尝试让我的 React Web-App NavBar 链接到我的应用程序内的其他页面。

我尝试过的:

  1. 在我的 App.js 文件中,我已经设置了 React-Router-Dom,如您所见。
  2. 我还在我的导航栏中插入了链接
  3. 现在,我在本地服务器上查看网站时遇到问题。 (见截图)

这是App.js的代码

import React from "react"
import NavBar from "./NavBar"
import Dashboard from "./Dashboard"
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";

function App() {
    return (
        <Router>
        <div>
            <NavBar />
            <Route path="/dashboard" component={Dashboard} />
        </div>
        </Router>
        )
}

export default App

这是导航栏的代码

import React from "react"
import "./Style.css"
import { link } from 'react-router-dom'

class NavBar extends React.Component {
    render() { return (

        <nav>
            <h1 className="h1">Hello</h1>
            <ul>
                <link to={"./Dashboard"}>
                    <li>Dashboard</li>
                </link>
            </ul>
        </nav>
    ) 
    }
}

export default NavBar

这是错误的屏幕截图: enter image description here

reactjs react-router navigation linker
5个回答
10
投票

您使用链接的方式错误


import {Link} from "react-router-dom";

<Link to="/Dashboard"> Dashboard </Link>

使用这个看看是否有效


2
投票

导入和 JSX 中链接组件都必须以大写字母 L 开头。

  import { Link } from 'react-router-dom'
  
  <Link to={"./Dashboard"}>
    Dashboard
  </Link>

阅读更多内容https://reactrouter.com/web/api/Link,还有一些示例。

顺便说一句:链接应该在li

里面

0
投票

在 app.js 文件中:添加如下所示的 Switch Router 并添加确切的单词到路由

 return (
    <Router>
    <div>
        <NavBar />
         <Switch>
        <Route exact path="/dashboard" component={Dashboard} />
       </Switch>
    </div>
    </Router>
    )

导出默认应用程序

在导航栏文件中:按照说明进行更改。

return (

    <nav>
        <h1 className="h1">Hello</h1>
        <ul>
              <li><link to="/dashboard">Dashboard<link></li>
        </ul>
    </nav>
) 

注意:它不是 /Dashboard 它的 /dashboard 就像你提到的那样

导出默认导航栏


0
投票

在 App.js 中,使用

<main>
        <Switch>
          <Route exact path="/" component={HomeScreen}/>
          <Route exact path="/product/:id" component={ProductScreen}/>
          <Route exact path="/cart" component={CartScreen}/>
          
        </Switch>
      </main>

0
投票
import {Link} from "react-router-dom";
import { Button } from "react-bootstrap";

<Link to="/Home">
    <Button>Click to home page<Button>
</Link>
© www.soinside.com 2019 - 2024. All rights reserved.