React - 路由 NavLink 使用 与 NavLink 组件封装使用(路由高亮)
一. NavLink 理解
NavLink 可以实现路由的高亮,通过 activeClassName 属性指定样式名(应避免使用 active )。- 标签体内容是一个特殊的标签属性。
- 通过
this.props.children 可以获取标签体内容。
二. NavLink 使用
import React, { Component } from "react";
import { Route, NavLink } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import "./app.css";
export default class App extends Component {
render() {
return (
<div className="wrap">
<div className="left">
{}
<ul>
<li>
<NavLink
className="link_item"
activeClassName="link_active"
to="home"
>
Home
</NavLink>
</li>
<li>
<NavLink
className="link_item"
activeClassName="link_active"
to="about"
>
About
</NavLink>
</li>
</ul>
</div>
<div className="right">
{}
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
</div>
</div>
);
}
}
app.css
.wrap {
width: 100%;
height: 100%;
display: flex;
}
.left {
width: 200px;
height: 100%;
border-right: 1px solid #bbb;
box-sizing: border-box;
}
ul {
list-style: none;
}
li {
width: 100%;
height: 40px;
line-height: 40px;
border-bottom: 1px solid #bbb;
}
.link_item {
width: 100%;
height: 100%;
display: block;
}
.link_active {
color: red !important;
background-color: aquamarine !important;
}
.right {
width: calc(100% - 200px);
}
三. NavLink 封装使用
import React, { Component } from "react";
import { Route } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import MyNavLink from "./components/MyNavLink";
import "./app.css";
export default class App extends Component {
render() {
return (
<div style={{ width: "100%", height: "100%", display: "flex" }}>
<div
style={{
width: "200px",
height: "100%",
borderRight: "1px solid",
boxSizing: "border-box",
}}
>
{}
<ul style={{ listStyle: "none" }}>
<li
style={{
width: "100%",
height: "40px",
lineHeight: "40px",
borderBottom: "1px solid #bbb",
}}
>
<MyNavLink to="home">Home</MyNavLink>
</li>
<li
style={{
width: "100%",
height: "40px",
lineHeight: "40px",
borderBottom: "1px solid #bbb",
}}
>
<MyNavLink to="about">About</MyNavLink>
</li>
</ul>
</div>
<div style={{ width: "calc(100% - 200px)", height: "100%" }}>
{}
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
</div>
</div>
);
}
}
MyNavLink
import React, { Component } from "react";
import { NavLink } from "react-router-dom";
export default class MyNavLink extends Component {
render() {
console.log(this.props);
return (
<NavLink
activeStyle={{
color: "#fff",
background: "#03a9f4",
}}
style={{
width: "100%",
height: "100%",
display: "block",
}}
{...this.props}
/>
);
}
}
|