什么是高阶组件(HOC):
入参是一个组件,同时返回的也是一个组件,这类组件被称为高阶组件
withRouter让不具备路由切换功能的组件,能够具有路由切换组件的三个属性
location、match、history
withRouter监听URI,每当URL变化的时候,都能获取到变化后的URI
import React from 'react';
import logo from './logo.svg';
import './App.css';
//引入Route,使用路由
import { Route, withRouter } from 'react-router-dom'
import Home from "./model/Home"
import News from "./model/News"
import Phone from "./model/Phone"
function App(props) {
//监听uri变化,并获取改变后的uri
props.history.listen((uri) => {
console.log(uri);
});
return (
<div className="App">
<a href="/#/Home">Home</a><br />
<a href="/#/News">News</a><br />
<a href="/#/Phone">Phone</a><br />
<Route path="/Home" component={Home} />
<Route path="/News" component={News} />
<Route path="/Phone" component={Phone} />
</div>
);
}
//在App组件上使用withRouter,让他也具备location、match、history三个属性
export default withRouter(App);
如图所示,你每一次的URI变化都会变监听到
页面跳转
import React from 'react';
import logo from './logo.svg';
import './App.css';
//引入Route,使用路由
import { Route, withRouter } from 'react-router-dom'
import Home from "./model/Home"
import News from "./model/News"
import Phone from "./model/Phone"
function App(props) {
return (
<div className="App">
{/* 手动跳转页面 */}
<button type="button" onClick={() => { props.history.push("/Home")}}>点我去Home</button>
<button type="button" onClick={() => { props.history.push("/News")}}>点我去News</button>
<button type="button" onClick={() => { props.history.push("/Phone")}}>点我去Phone</button>
<Route path="/Home" component={Home} />
<Route path="/News" component={News} />
<Route path="/Phone" component={Phone} />
</div>
);
}
//在App组件上使用withRouter,让他也具备location、match、history三个属性
export default withRouter(App);
路由传参的方式:
Params方式进行传参:
1. 需要在路由规则中设置传递的接收参数
2. 在跳转路径上发送参数
3. 通过 props.match.params.参数名 来取值
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
//引入Route,使用路由
import { Route, withRouter } from 'react-router-dom'
import Home from "./model/Home"
import News from "./model/News"
import Phone from "./model/Phone"
function App(props) {
return (
<div className="App">
{/* 手动跳转页面 */}
<button type="button" onClick={() => { props.history.push("/News/我是参数哦")}}>点我去News</button>
{/* 接受入参value */}
<Route path="/News/:value" component={News} />
</div>
);
}
//在App组件上使用withRouter,让他也具备location、match、history三个属性
export default withRouter(App);
News.jsx
import React, { Component } from 'react'
import PubSub from "pubsub-js"
export default class News extends Component {
componentDidMount(){
//打印接收到的参数
console.log(this.props.match.params.value);
}
render() {
return (
<div>
<h1>News组件</h1>
</div>
)
}
}
效果: