1安装react-router-dom npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令 1 新建router文件 //引入 react-router-dom import { HashRouter, Route, Switch, BrowserRouter as Router } from "react-router-dom"; //分别添加两个页面 import App from '../App'; import Home from '../Home'; const BasicRoute = () => ( <Router> <Switch> <Route exact path="/" component={App} activeClassName="active"/> <Route exact path="/home" component={Home} activeClassName="active"/> </Switch> </Router> ); export default BasicRoute;
2 index.js //引入路由 import Router from './router/router'; //首先渲染的component ReactDOM.render(<Router/>, document.getElementById('root')); 3 路由的跳转 import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom"; <Link to="/home">home</Link> <input type="button" value="Home" onClick={this.goHome.bind(this)}/> state 隐式传参 <Link to={{ pathname:'/home',state:{ type: 'id' }}} >home</Link> query 隐式传参 <Link to={{ pathname:'/home',query:{ type: 'id' }}} >home</Link>
{/* 离开页面时提示*/}
<Prompt message="您确定要离开该页面吗?" /> 方法跳转
goHome() { this.props.history.push({ pathname: '/Home', state: { id: 3 } }) }
//子页面 接受传值 (不同方式下的接受方式)
componentWillMount() {
let _id = this.props.match.params.id,
id = this.props.history.location.state,
id1 = this.props.history.location.query;
console.log("准备好了", _id, id, id1);
};