简体   繁体   English

为什么我的 React Router 组件采用了错误的样式?

[英]Why is my React Router component taking the wrong style?

I'm using react-router and I separated it as its own component and it works fine but the only issue is that the text from that said routed page appears in the navbar.我正在使用 react-router 并将其分离为自己的组件,它工作正常,但唯一的问题是来自该路由页面的文本出现在导航栏中。 I'm relatively new to React so if there's anything I'm doing wrong that could be done better, I would love to know!我对 React 比较陌生,所以如果我做错了什么可以做得更好,我很想知道!

Code Sandbox 代码沙箱

You could move Switch to Home.js :您可以将Switch移至Home.js

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

class Home extends React.Component {
  render() {
    return (
      <div>
      <Router>
        <HomeNav />
        <h1>
          "this is the friends/account tab" <br />text should be here
        </h1>
          <Switch>
            <Route path="/account" component={Account} />
            <Route path="/friends" component={Friends} />
          </Switch>
      </Router>
      </div>
    );
  }
}

export default Home;

Only put links in Routing.js仅在Routing.js中放置链接

class Routing extends React.Component {
  render() {
    return (
        <div>
          <ul>
            <li>
              <Link to="/friends">friends</Link>
            </li>

            <li>
              <Link to="/account">account</Link>
            </li>
          </ul>
        </div>
    );
  }
}

In my understanding is that the component is only showed where the Switch declared.据我了解,该组件仅显示在Switch声明的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM