1.安装react-router-dom
1.1 在项目命令行中,执行
npm install react-router-dom-S
下载到生产环境依赖中。
2.路由内置组件
HashRouter
表示一个路由的跟容器,将来所有跟路由相关的东西,都要包裹在HashRouter中,一个网站中,只需要使用一次HashRouter就好了。
Link
表示一个路由的连接;
Route
表示一个路由规则;
1 render(){ 2 return ( 3 <HashRouter> 4 <div> 5 <h1>这是网站的根目录</h1> 6 <hr /> 7 <Link to="/new">首页</Link> 8 <Link to="/movie/">新闻</Link> 9 <Link to="/about">关于我们</Link> 10 <hr /> 11 <Route path="/home" component={HOME} ></Route><hr/> 12 <Route path="/new" component={New} exact></Route><hr/> 13 <Route path="/about" component={About}></Route><hr/> 14 </div> 15 </HashRouter> 16 ); 17 }
由Route创建的标签,就是路由规则,其中path表示要匹配的路由,component表示要展示的组件。
Route具有两种身份:
1.它是一个路由匹配规则;
2.它是一个占位符,表示将来匹配到的组件都放到这个位置
注意:
Link to属性的地址也是/开头,Link在页面渲染的是a标签;
Route 组件path地址是以/开头 ,配置component属性,是显示的组件,这个属性不可以大写;
嵌套路由:在路由组件中,使用Link,Route,配置子路由,实现跳转,切换;
下面为一级路由,在一级路由New为路由组件
1 <Route path="/new" component={ New }></Route> 2 3 render (){ 4 return( 5 <React.Fragment> 6 《新闻》 7 <ul> 8 <li> 9 <Link to="/new/act">今日聚焦</Link> 10 </li> 11 <li> 12 <Link to="/new/three">三农信息</Link> 13 </li> 14 <li> 15 <Link to="/new/week">新闻周刊</Link> 16 </li> 17 </ul> 18 <Route path="/new/act" component={Act}></Route> 19 <Route path="/new/three" component={Three}></Route> 20 <Route path="/new/week" component={Week}></Route> 21 22 </React.Fragment> 23 ) 24 }
4.带参数路由和获取参数
通过配置路由的地址,在Link跳转时
Route path路径后面 /:id (key)
Link to 路径后面 /top/10 (value)
接收传值:
class类组件,this.props.match.params.属性名
函数组件:形参.match.params.属性名
代码实例:
1 render(){ 2 return ( 3 <HashRouter> 4 <div> 5 <h1>网站根目录</h1> 6 <hr /> 7 <Link to="/about/add/5497">关于我们</Link> 8 <hr /> 9 <Route path="/about/:type/:id" component={Movie} exact></Route> 10 </div> 11 </HashRouter> 12 ); 13 }
在Route内置组件中,配置path地址
1 <Route path="/about/:type/:id" component={Movie}></Route> 2 3 //在Link内置组件中,配置to属性,进行跳转: 4 5 <Link to="/about/active/5497"></Link> 6 7 //类组件中通过声明周期进行接收this.props传递过来的数据 8 9 render(){ 10 console.log(this); 11 return ( 12 <div> 13 电影--{this.props.match.params.type}--{this.props.match.params.id} 14 </div> 15 ); 16 }
5. HashRouter和BrowserRouter的区别
React-Router 是建立在 history 之上的,常见的history路由方案有三种形式,分别是:
HashRouter、BrowserRouter、Route、Link、HashRouter和BrowserRouter的区别;
原文:https://www.cnblogs.com/jiazhaolong/p/12099667.html