基本上,我正在学习与react-router-dom
,version 5.0.0
的React Routing,我有一些组件,如Home,About,Contact等。我试图通过点击NavLink来改变每个组件但不改变组件只是更改URL
Indexjs:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './Style.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import Header from "./components/Header";
import Footer from "./components/Footer";
import Web from "./Web";
ReactDOM.render(
<React.Fragment>
<Header />
<Web />
<Footer />
</React.Fragment>
, document.getElementById('root'));
serviceWorker.register();
Web组件:
import React, {Component} from 'react';
import {BrowserRouter as Router, Route, Link, NavLink, Redirect, Switch,withRouter} from "react-router-dom";
//import Route from 'react-router-dom/Route';
import {Home} from "./components/Home";
import {About} from "./components/About";
import {Contact} from "./components/Contact";
import {Products} from "./components/Products";
class Web extends Component {
render() {
return (
<Router>
<Switch>
<Route path={"/"} exact component={withRouter(Home)}/>
<Route path={"/products"} component={withRouter(Products)}/>
<Route path={"/about"} component={About}/>
<Route path={"/contact"} component={Contact}/>
<Route path={"/something"} render={
() => {
return (<h1>This is something page</h1>);
}
}/>
</Switch>
</Router>
);
}
}
export default Web;
标题组件:
import React, { Component } from 'react';
import logo from '../logo.jpg';
import {BrowserRouter as Router, Route, Link, NavLink, Redirect} from "react-router-dom";
class Header extends Component {
render() {
return(
<Router>
<header className={'header_area'}>
<div className="container">
<div className="logo">
<a href="/"><img src={logo} alt="logo"/></a>
</div>
<nav className={'main_nav'}>
<ul>
<li><NavLink to="/" activeStyle={{color:"green"}} exact>Home</NavLink></li>
<li><NavLink to="/products" activeStyle={{color:"green"}} exact>Products</NavLink></li>
<li><NavLink to="/about" activeStyle={{color:"green"}} exact>About</NavLink></li>
<li><NavLink to="/contact" activeStyle={{color:"green"}} exact>Contact</NavLink></li>
</ul>
</nav>
<div className="float_clear"></div>
</div>
</header>
</Router>
);
}
}
export default Header;
主页组件:
import React from 'react';
export class Home extends React.Component {
render() {
return (
<React.Fragment>
<article className={'article_area'}>
<div className="container article">
<h2>Home</h2>
</div>
</article>
</React.Fragment>
);
}
}
关于组件:
import React from 'react';
export class About extends React.Component {
render() {
return (
<React.Fragment>
<article className={'article_area'}>
<div className="container article">
<h2>About us</h2>
</div>
</article>
</React.Fragment>
);
}
}
谁能帮我?
您应该使用单个Router
,并且您的所有路线和链接都应该将其作为其父母之一。
更改索引:
<React.Fragment>
<Router>
<Header />
<Web />
<Footer />
</Router>
</React.Fragment>
并删除其他<Router>
s
此外,您不需要使用withRouter
作为Route
内的组件。他们将直接获得react-router道具。