安装模块 react-router-dom
导出组件 { HashRouter, Route,Link,Switch } from 'react-router-dom'
用列:
<HashRouter>
<Route render={({ location }) => (
<ReactCSSTransitionGroup
transitionName="example"
component="div"
transitionEnterTimeout={0}
transitionLeaveTimeout={0}>
<div className='app' key={Math.random()*10000+Math.random()*10000+Math.random()*10000}>
<Header />
<div className="common-content">
<Switch>
<Route exact path="/" location={location} key={location.key} component={Welcome} / >
<Route location={location} key={location.key} path="/home" component={Home} / >
<Route location={location} key={location.key} path="/change-table" component={NoteAndTable} / >
<Route location={location} key={location.key} component={Error} / >
</Switch>
</div>
</div>
</ReactCSSTransitionGroup>
)}/>
</HashRouter>
HashRouter 是路由器上所使用的url 类型 也可以使用
BrowserHistory (自己觉得
BrowserHistory 只能跑服务端,打包后在本地没有后台的情况下不能用)
作用: 保持你的 ui 和 url 同步(这个指令上有几个配置属性,一般情况下我都不写)
Route 有三种渲染内容的方法:
- <Route component> 大多数情况使用这种方法根据component={组件名} 的组件创建一个新的React element
- <Route render> render=function 你可以选择传一个在地址匹配时被调用的函数,而不是像使用component属性那样得到一个新创建的React element。使用render属性会获得跟使用component属性一样的route props
- <Route children > 有时候你可能想不管地址是否匹配都渲染一些内容,这种情况你可以使用children属性。它与render属性的工作方式基本一样,除了它是不管地址匹配与否都会被调用。除了在路径不匹配URL时match的值为null之外,children渲染属性会获得与component和render一样的route props。这就允许你根据是否匹配路由来动态地调整UI了,来看这个例子,如果理由匹配的话就添加一个active类:
Route 其他属性
path: 路由名字 (string)
exact: 默认为false 为true 就是url上的路由需要与 所写路由完全相同
strict: 为true结尾有/ 只能匹配 有斜线结尾的url
Switch 组件 是为了用当用户在写的路由在路由配置里面没有的时候显示404界面
当使用 Switch组件时候需要配置一个没有path 路由 component={404组件名}
这样基本上就能使用 react-router v4了
ReactCSSTransitionGroup 这个组件是 页面切换时候的动画组件 需要的可以上网查查