React-router 基本用法
转载自 阮一峰的网络日志 (ruanyifeng.com)
React-router
路由库: ReactTraining/react-router: Declarative routing for React (github.com)
示例库: react-router-tutorial/lessons at master · reactjs/react-router-tutorial (github.com)
文 档: React Router 使用教程 - 阮一峰的网络日志 (ruanyifeng.com)
一、安装:
npm install -S react-router
二、用法:
基础用法
import { Router, Route, hashHistory } from 'react-router';
render((
<Router history={ hashHistory}>
<Route path="/" component={ App}/>
</Router>
), document.getElementById('app'));
路由嵌套:
// index.js
<Router history={ hashHistory}>
<Route path="/" component={ App}>
<Route path="/repos" component={ Repos}/>
<Route path="/about" component={ About}/>
</Route>
</Router>
// App.js
export default React.createClass({
render() {
return <div>
{ this.props.children}
</div>
}
})
// 相当于 先加载App组件,然后在它内部加载Repos组件
<App>
<Repos/>
</App>
routes属性
子路由也可以不写在Router
组件里面,单独传入Router
组件的routes
属性。
let routes = <Route path="/" component={ App}>
<Route path="/repos" component={ Repos}/>
<Route path="/about" component={ About}/>
</Route>;
<Router routes={ routes} history={ browserHistory}/>
三、path属性
Route
组件的path
属性指定路由的匹配规则。这个属性是可以省略的,这样的话,不管路径是否匹配,总是会加载指定组件。
<Route path="inbox" component={ Inbox}>
<Route path="messages/:id" component={ Message} />
</Route>
// 结果一样
<Route component={ Inbox}>
<Route path="inbox/messages/:id" component={ Message} />
</Route>
四、通配符
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
paramName
匹配URL的一个部分,直到遇到下一个/
?
#
为止。这个路径参数可以通过this.props.params.paramName
取出。()
表示URL的这个部分是可选的*
匹配任意字符,直到模式里面的下一个字符为止。匹配方式是非贪婪模式。**
匹配任意字符,直到遇到下一个/
?
#
为止。匹配方式是贪婪模式。
path
属性也可以使用相对路径(不以/
开头),匹配时就会相对于父组件的路径,可以参考上一节的例子。嵌套路由如果想摆脱这个规则,可以使用绝对路由。
路由匹配规则是从上到下执行,一旦发现匹配,就不再其余的规则了。
注意:设置路径参数时,需要特别小心这一点。
<Router>
<Route path="/:userName/:id" component={ UserPage}/>
<Route path="/about/me" component={ About}/>
</Router>
上面代码中,用户访问/about/me
时,不会触发第二个路由规则,因为它会匹配/:userName/:id
这个规则。因此,带参数的路径一般要写在路由规则的底部。
此外,URL的查询字符串/foo?bar=baz
,可以用this.props.location.query.bar
获取。
五、IndexRoute 组件
显式指定Home
是根路由的子组件,即指定默认情况下加载的子组件。你可以把IndexRoute
想象成某个路径的index.html
。
<Router>
<Route path="/" component={ App}>
<IndexRoute component={ Home}/>
<Route path="accounts" component={ Accounts}/>
<Route path="statements" component={ Statements}/>
</Route>
</Router>
在访问/
的时候,加载app组件再加载home组件。<App><Home/></App>
注意,IndexRoute
组件没有路径参数path
。
六、Redirect 组件
Redirect
组件用于路由的跳转,即用户访问一个路由,会自动跳转到另一个路由。
<Route path="inbox" component={ Inbox}>
{ /* 从 /inbox/messages/:id 跳转到 /messages/:id */}
<Redirect from="messages/:id" to="/messages/:id" />
</Route>
// 访问/inbox/messages/5,会自动跳转到/messages/5。
七、IndexRedirect 组件
IndexRedirect
组件用于访问根路由的时候,将用户重定向到某个子组件。
<Route path="/" component={ App}>
<IndexRedirect to="/welcome" />
<Route path="welcome" component={ Welcome} />
<Route path="about" component={ About} />
</Route>
用户访问根路径时,将自动重定向到子组件welcome
。
八、Link
Link
组件用于取代元素,生成一个链接,允许用户点击后跳转到另一个路由。它基本上就是
元素的React 版本,可以接收Router
的状态。
如果希望当前的路由与其他路由有不同样式,这时可以使用Link
组件的activeStyle
属性。
<Link to="/about" activeStyle={ { color: 'red'}}>About</Link>
<Link to="/repos" activeStyle={ { color: 'red'}}>Repos</Link>
使用activeClassName
指定当前路由的Class
。
<Link to="/about" activeClassName="active">About</Link>
<Link to="/repos" activeClassName="active">Repos</Link>
在Router
组件之外,导航到路由页面,可以使用浏览器的History API,像下面这样写。
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
九、IndexLink
如果链接到根路由/
,不要使用Link
组件,而要使用IndexLink
组件。
这是因为对于根路由来说,activeStyle
和activeClassName
会失效,或者说总是生效,因为/
会匹配任何子路由。而IndexLink
组件会使用路径的精确匹配。
<IndexLink to="/" activeClassName="active">
Home
</IndexLink>
上面代码中,根路由只会在精确匹配时,才具有activeClassName
。
另一种方法是使用Link
组件的onlyActiveOnIndex
属性,也能达到同样效果。
<Link to="/" activeClassName="active" onlyActiveOnIndex={ true}>
Home
</Link>
实际上,IndexLink
就是对Link
组件的onlyActiveOnIndex
属性的包装。
十、histroy 属性
Router
组件的history
属性,用来监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配。
history属性值:
browserHistory
浏览器的路由就不再通过Hash
完成了,而显示正常的路径example.com/some/path
,背后调用的是浏览器的History API。hashHistory
路由将通过URL的hash部分(#
)切换,URL的形式类似example.com/#/some/path
。createMemoryHistory
主要用于服务器渲染。它创建一个内存中的history
对象,不与浏览器URL互动。
使用 browserHistory 属性时:
需要对服务器进行修改【如:nginx配置】。否则用户直接向服务器请求某个子路由,会显示网页找不到的404错误。
如果开发服务器使用的是webpack-dev-server
,加上--history-api-fallback
参数就可以了。
webpack-dev-server --inline --content-base . --history-api-fallback
十一、表单处理
Link
组件用于正常的用户点击跳转 ,但是有时还需要表单跳转、点击按钮跳转等操作。这些情况怎么跟React Router对接呢? [在方法中进行跳转]
第一种方法是使用browserHistory.push
import { browserHistory } from 'react-router'
// ...
handleSubmit(event) {
event.preventDefault()
browserHistory.push('/repos')
}
第二种方法是使用context
对象
export default React.createClass({
// ask for `router` from context
contextTypes: {
router: React.PropTypes.object
},
handleSubmit(event) {
// ...
this.context.router.push(path)
},
})
十二、路由的钩子
每个路由都有Enter
和 Leave
钩子,用户进入和离开该路由时触发。
下面是一个例子,使用onEnter
钩子替代Redirect
组件。
<Route path="inbox" component={ Inbox}>
<Route
path="messages/:id"
onEnter={
({ params}, replace) => replace(`/messages/${ params.id}`)
}
/>
</Route>
onEnter
钩子还可以用来做认证。
const requireAuth = (nextState, replace) => {
if (!auth.isAdmin()) {
// Redirect to Home page if not an Admin
replace({ pathname: '/' })
}
}
export const AdminRoutes = () => {
return (
<Route path="/admin" component={ Admin} onEnter={ requireAuth} />
)
}
下面是一个高级应用,当用户离开一个路径的时候,跳出一个提示框,要求用户确认是否离开。
const Home = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
},
routerWillLeave(nextLocation) {
// 返回 false 会继续停留当前页面,
// 否则,返回一个字符串,会显示给用户,让其自己决定
if (!this.state.isSaved)
return '确认要离开?';
},
})
)
上面代码中,setRouteLeaveHook
方法为Leave
钩子指定routerWillLeave
函数。该方法如果返回false
,将阻止路由的切换,否则就返回一个字符串,提示用户决定是否要切换。
还没有评论,来说两句吧...