path通配符:
<Route path="/hello/:name">
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/hello(/:name)">
// 匹配 /hello
// 匹配 /hello/michael
// 匹配 /hello/ryan
<Route path="/files/*.*">
// 匹配 /files/hello.jpg
// 匹配 /files/hello.html
<Route path="/files/*">
// 匹配 /files/
// 匹配 /files/a
// 匹配 /files/a/b
<Route path="/**/*.jpg">
// 匹配 /files/hello.jpg
// 匹配 /files/path/to/file.jpg
router路由的匹配规则为从上到下,如果有两个相同的路由,会匹配第一个,第二个无效。
router常用组件如下:
Link
Link
组件用于取代<a>
元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是<a>
元素的React 版本,可以接收Router
的状态。
render(){
return (
<ul>
<li><Link to="/haha">哈哈</Link></li>
</ul>
)
}
增加样式
<Link to="/haha" activeStyle={{ color: #f00 }}></Link>
增加class
<Link to="/haha" activeclassName></Link>
IndexRoute
<Router>
<Route dath="/" component={App}>
<Route
dath="about" component={About}></Route>
<Route
dath="con" component={Con}></Route>
</Route>
</Router>
访问根路由“/”时,不会加载任何子组件,<IndexRoute component={Home}></IndexRoute>,这样,访问根路径时会直接加载Home组件,相当于给根路由默认指定了一个组件来加载
注意:IndexRoute组件没有路径参数dath.
IndexLink
加载根路由'/'时,activeclassName和activeStyle会失效,或者说总是生效,因为它会匹配根路由下的所有子路由,而IndexLink会使用路由的精确匹配,不会出错
<IndexLink activeStyle={{color: '#f00'}} activeclassName="font"></IndexLink>
Redirect
从当前路由跳转到另一个路由
<Redirect from="/a" to="/b"></Redirect> 从"/a"跳转到"/b"
IndexRedirect
访问根路由"/"时,将路径指向某个特定的子路由。
<Rouder>
<Roude dath="/" component={App}>
<IndexRedirect to="/about"></IndexRedirect>
<Route dath="/about" component={About}></Route>
</Roude>
</Rouder>
history
history属性用来监听地址栏的变化,一般分为3种
hashHistory
- browserHistory
- createMemoryHistory
hashHistory: <Router history={hashHistory} routes={routes}> 通过路由的hash部分切换 #
browserHistory: <Router history={browserHistory} routes={routes}></Router> 显示正常的路径,背后调用的是浏览器的History API,但是这种情况需要对服务器进行改造,否则用户直接向服务器请求某个子路由,会导致找不到网页的404错误,
如果开发服务器使用的是webpack-dev-server,加上--history-api-fallback参数就可以了。
$ webpack-dev-server --inline--content-base . --history-api-fallback
createMemoryHistory: 主要用于服务器渲染,不与浏览器url互动 const history=createMemoryHistory(location)
表单处理
<form>
<input type="text" placeholder="name" />
<input type="password" placeholder="password" />
</form>