实现思路:
1、定义一个普通组件
2、普通组件内使用NavLink
3、传递参数给定义的普通组件并实现效果
代码实现:
App.jsx
import React, { Component } from "react";
import About from "../src/Pages/About";
import Home from "../src/Pages/Home";
import MyNavLink from "./Compentens/MyNavLink";
import { NavLink, Route, Redirect } from "react-router-dom";
import "./App.css";
export default class App extends Component {
render() {
return (
<div>
<h1>React Router Demo</h1>
<div className="list-group">
{/* 开始封装 */}
{/* <MyNavLink to="/home">Home</MyNavLink> ===
<MyNavLink to="/home" children="Home"/> */}
<MyNavLink to="/home">Home</MyNavLink>
<MyNavLink to="/about">About</MyNavLink>
</div>
<div>
{/* 注册路由 */}
<Route path="/home" component={Home}></Route>
<Route path="/about" component={About}></Route>
{/* 路由重定向 */}
<Redirect to="/home"></Redirect>
</div>
</div>
);
}
}
MyNavLink.jsx
import React, { Component } from "react";
import { NavLink } from "react-router-dom";
export default class MyNavLink extends Component {
render() {
console.log(this.props);
return (
<NavLink
activeClassName="aiguigu"
className="list-group-item w-25"
{...this.props}
/>
);
}
}
Home.jsx
import React, { Component } from "react";
export default class index extends Component {
render() {
return (
<div>
<h3>我是Home的内容</h3>
</div>
);
}
}
About.jsx
import React, { Component } from 'react'
export default class index extends Component {
render() {
console.log('我是About的内容',this.props);
return (
<h3>我是About的内容</h3>
)
}
}
实现效果:
总结:
1、书写代码时,应该注意降低代码的重复率,高效率解决问题。
2、在项目开发中可以多加尝试用二次封装,来提高项目开发能力。