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

我正在使用 react-router,我将它作为自己的组件分离出来,它工作正常,但唯一的问题是来自该路由页面的文本出现在导航栏中。我是 React 的新手,所以如果我做错了什么可以做得更好,我很想知道!

代码沙盒


Cats萌萌
浏览 58回答 1
1回答

白猪掌柜的

你可以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 {&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <Router>&nbsp; &nbsp; &nbsp; &nbsp; <HomeNav />&nbsp; &nbsp; &nbsp; &nbsp; <h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "this is the friends/account tab" <br />text should be here&nbsp; &nbsp; &nbsp; &nbsp; </h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/account" component={Account} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/friends" component={Friends} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Switch>&nbsp; &nbsp; &nbsp; </Router>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}export default Home;只放链接Routing.jsclass Routing extends React.Component {&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Link to="/friends">friends</Link>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Link to="/account">account</Link>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}据我了解,组件仅在Switch声明的位置显示。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript