###React Web:使用Router实现页面跳转、传参
####1.效果展示
####2 . npm导入react-router并添加依赖
(shift+右键项目根目录,打开命令行输入以下内容)
npm install react-router --save-dev
####3.新建两个子页面
Red.js
import ReactDOM,{render} from 'react-dom'
export default class Red extends Component{
render(){
return <div>Red</div>
}
}
####4.Router实现
Index.js
import React,{Component} from 'react'
import ReactDOM,{render} from 'react-dom'
import { Router, Route, hashHistory,Link } from 'react-router';
import Red from './Red'
import Blue from './Blue'
class MyApp extends Component{
render(){
return(
<div>
<h3>This is index(MyApp)</h3>
<Link to="/red"><h3>toRed</h3></Link>
<Link to={"/blue/"+20}><h3>toBlue</h3></Link>
</div>
);
}
}
render((
<Router history={hashHistory}>
<Route path="/" component={MyApp}/>
<Route path="/red" component={Red}/>
<Route path="/blue/:id" component={Blue}/>
</Router>
), document.getElementById('app'));
6.添加<Link>
标签
react的<Link>
标签在浏览器上会被渲染为<a>
标签
<Link to="/red"><h3>toRed</h3></Link>
7.传参
在Router内新增一句(id即是要传的参数名)
<Route path="/blue/:id" component={Blue}/>
同样对“toBlue”加上<Link>
标签,区别是多了一斜杠和传递值,然后包裹上大括号,
<Link to={"/blue/"+20}><h3>toBlue</h3></Link>
8.接受参数
Blue.js
import ReactDOM,{render} from 'react-dom'
export default class Blue extends Component{
constructor(props){
super(props);
}
render(){
return <div>Blue:id:{this.props.params.id}</div>
};
}