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