参考REACT ROUTER官方文档 https://reacttraining.com/react-router/
新的React-Router相比于之前的有很大变化,主要思想为一切皆组件,路由也是个组件,react-router是核心,下面分为react-router-dom对应web页面开发,react-router-native对应native应用开发。
React-Router共有三类组件
路由容器组件: 包含 <BrowserRouter>和<HashRouter>
如果你有对应的请求服务器,建议使用 <BrowserRouter>,如果只是一个静态服务器,则使用<HashRouter>
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
holder
);
路由匹配组件: 包含<Route>和<Switch>
<Switch>组件是包裹着<Router>容器,一旦匹配到就停止往下继续匹配
<Route>即路由组件,常见有两种应用 component和Render
<Switch>
<Routeexactpath="/"component={Home}/>
<Routepath="/about"component={About}/>
<Routepath="/contact"render={()=><div>contact</div>}
</Switch>
路由导航组件: 包含<Link>和<NavLink>
<NavLink>是<Link>的封装,增加了激活状态下样式接口
<Link to="/">Home</Link>
// <a href='/'>Home</a>
<NavLink to="/react" activeClassName="hurray">
React
</NavLink>
// <a href='/react' className='hurray'>React</a>
基本应用参考:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function BasicExample() {
return (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li> <Link to="/topics">Topics</Link></li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
}
function Home() {
return (
<div>Home</div>
);
}
function About() {
return (
<div>About</div>
);
}
function Topics({ match }) {
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<Route path={`${match.path}/:topicId`} component={Topic} />
<Route
exact
path={match.path}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
}
function Topic({ match }) {
return (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
}
export default BasicExample;
网友评论