NavLink
当我们希望给当前的路由添加一个样式的时候,可以使用NavLink模块来代替Link模块
给NavLink添加activeClassName属性,属性名为class名,在样式中定义active样式
App.js
import { PureComponent } from "react";
import './App.css'
// 引入Route模块
import { NavLink, Route } from 'react-router-dom'
import Course from './Course.js'
import Home from './Home.js'
class App extends PureComponent {
render() {
return (
<div id="app">
<NavLink activeClassName="active" to="/home">首页</NavLink>
<NavLink activeClassName="active" to="/course">课程</NavLink>
{/* 路由出口 */}
<Route path="/home" component={Home}></Route>
<Route path="/course" component={Course}></Route>
</div>
)
}
}
export default App
App.css
a{
text-decoration: none;
margin: 0 10px;
}
.active{
color: #c00;
}
路由重定向
我们希望一进入页面就可以访问到/home页面,使用Redirect模块
import { PureComponent } from "react";标签:---,NavLink,App,js,React,Home,import,路由 From: https://www.cnblogs.com/toufuwqm/p/16916989.html
import './App.css'
// 引入Route模块
import { NavLink, Route, Redirect } from 'react-router-dom'
import Course from './Course.js'
import Home from './Home.js'
class App extends PureComponent {
render() {
return (
<div id="app">
<NavLink activeClassName="active" to="/home">首页</NavLink>
<NavLink activeClassName="active" to="/course">课程</NavLink>
{/* 路由出口 */}
<Route path="/home" component={Home}></Route>
<Route path="/course" component={Course}></Route>
{/* 访问根路径的时候,重定向到/home */}
<Redirect from="/" to="/home"></Redirect>
</div>
)
}
}
export default App