路由
npm i --save react-router-dom #功能更全
hash模式
import { HashRouter, Route, Link } from "react-router-dom";
render() {
return (
<HashRouter>
<div>
<header className="title">
<Link to="/">首页</Link>
<Link to="/news">新闻</Link>
<Link to="/product">商品</Link>
</header>
<br />
<hr />
<br />
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
<Route path="/product" component={Product} />
</div>
</HashRouter>
);
}
history模式
import { BrowserRouter as Router, Route, Link } from "react-router-dom"
render() {
return (
<Router>
<div>
<header className="title">
<Link to="/">首页</Link>
<Link to="/news">新闻</Link>
<Link to="/product">商品</Link>
</header>
<br />
<hr />
<br />
<Route exact path="/" component={Home} />
<Route path="/news" component={News} />
<Route path="/product" component={Product} />
</div>
</Router>
);
}
路由跳转和增加参数
import React, { Component } from 'react';
class News extends Component {
constructor(props) {
super(props);
this.data = {
value: null
};
}
componentWillMount(){
console.log('测试',this.data)
}
render(){
const btnNav = ()=> {
this.props.history.push({
pathname:'/',
search:'name'
});
}
return (
<div className="News">
当前是News页面
<button onClick={btnNav}>跳转到Home页面</button>
</div>
);
}
}
export default News;
# 明传
this.props.history.push({
pathname:'/',
search: 'name=1'
});
# 暗传
this.props.history.push({
pathname:'/',
state: { test: 'dashboard' }
});
# 接收参数
## Search
this.props.history.location.search
## State
this.props.history.location.state