react-router V4
- 概念:一个路由管理的组件库,包含多个路由组件
- 几个重要组件
- Router:管理路由的组件
- Route:注册路由,两个属性,path为路径,component为指向请求的组件
- Link:生成a标签,属性to为请求的路由
- Switch:包裹一组<Route>,将迭代其子元素路由,选择一个子路由进行渲染
- index.js
import React from 'react';
import ReactDOM from 'react-dom';
// BrowserRouter处理服务器动态请求使用 HashRouter处理只有静态文件的服务器网站
import {BrowserRouter as Router,Route,Switch} from "react-router-dom";
import About from "./components/About"
import App from "./components/App"
import Repos from "./components/Repos"
import Repo from "./components/Repo"
ReactDOM.render(
(
<Router>
<div>
{/* Route 注册路由,path为路径 component为指向的组件*/}
<Route path="/" component={App}/>
{/* Switch 包裹多个<Route>,对子元素路由进行迭代,仅渲染一个*/}
<Switch>
<Route path="/about" component={About}/>
{/* 注意这组件嵌套的用法*/}
<Repos> {/* 在这不能注册此组件的路由 否则,子组件内容不能显示 */}
{/* :name 为占位符写法,不确定参数值是什么*/}
<Route path="/repos/:name/:repo" component={Repo} />
</Repos>
</Switch>
</div>
</Router>
),
document.getElementById("root")
);
import React from "react"
import {Link} from "react-router-dom"
class App extends React.Component{
render() {
return(
<div>
<h2>App组件...</h2>
<ul>
<li>
{/*Link 生成a标签 属性to指向已经注册的路由*/}
<Link to="/about">about</Link>
</li>
<li>
<Link to="/repos">repos</Link>
</li>
</ul>
<hr/>
{/*显示子路由组件的数据内容*/}
{this.props.children}
</div>
)
}
}
export default App
import React from "react"
class Repo extends React.Component{
render() {
return(
<div>
{/* 获取路由中的参数 props.match.params.占位符名字*/}
公司:{this.props.match.params.name} 产品:{this.props.match.params.repo}
</div>
)
}
}
export default Repo
import React from "react"
import {Link} from "react-router-dom";
class Repos extends React.Component{
constructor(props){
super(props);
this.state = {
repos:[
{name:"google",repo:"github"},
{name:"antd",repo:"antd"},
{name:"facebook",repo:"react" }
]
}
}
render() {
let {repos} = this.state;
return(
<div>
<h2>Repos组件...</h2>
<ul>
{repos.map((item,index)=>{
return <li key={index}><Link to={`/repos/${item.name}/${item.repo}`}>{item.repo}</Link></li>
})}
</ul>
{/*显示子路由组件的数据内容*/}
{this.props.children}
</div>
)
}
}
export default Repos