Fix Breabcrumb link with router params, and no longer need prop router

This commit is contained in:
afc163 2016-01-23 20:12:09 +08:00
parent 3962d6e472
commit d1b06abdf5
3 changed files with 22 additions and 13 deletions

View File

@ -15,8 +15,12 @@ const Apps = React.createClass({
render() {
return (
<ul className="app-list">
<li><Link to="/apps/1">应用1</Link></li>
<li><Link to="/apps/2">应用2</Link></li>
<li>
<Link to="/apps/1">应用1</Link><Link to="/apps/1/detail">详情</Link>
</li>
<li>
<Link to="/apps/2">应用2</Link><Link to="/apps/2/detail">详情</Link>
</li>
</ul>
);
}
@ -39,7 +43,7 @@ const Home = React.createClass({
}}>
点击上面的导航切换页面,面包屑在下面:
</div>
<Breadcrumb {...this.props} router={ReactRouter} />
<Breadcrumb {...this.props} />
</div>
);
}
@ -49,7 +53,9 @@ ReactDOM.render(
<Router>
<Route name="home" breadcrumbName="首页" path="/" component={Home}>
<Route name="apps" breadcrumbName="应用列表" path="apps" component={Apps}>
<Route name="app" breadcrumbName="应用:id" path=":id" />
<Route name="app" breadcrumbName="应用:id" path=":id">
<Route name="detail" breadcrumbName="详情" path="detail" />
</Route>
</Route>
</Route>
</Router>

View File

@ -43,16 +43,14 @@ const Breadcrumb = React.createClass({
React.PropTypes.string,
React.PropTypes.element,
]),
router: React.PropTypes.object,
routes: React.PropTypes.array,
params: React.PropTypes.object
params: React.PropTypes.object,
},
render() {
let crumbs;
const { separator, prefixCls, router, routes, params, children } = this.props;
const ReactRouter = router;
if (routes && routes.length > 0 && ReactRouter) {
let Link = ReactRouter.Link;
const { separator, prefixCls, routes, params, children } = this.props;
if (routes && routes.length > 0) {
const paths = [];
crumbs = routes.map((route, i) => {
if (!route.breadcrumbName) {
return null;
@ -60,12 +58,18 @@ const Breadcrumb = React.createClass({
const name = route.breadcrumbName.replace(/\:(.*)/g, (replacement, key) => {
return params[key] || replacement;
});
let link;
const path = route.path.indexOf('/') === 0 ? route.path : ('/' + route.path);
let path = route.path.indexOf('/') === 0 ? route.path : ('/' + route.path);
Object.keys(params).forEach(key => {
path = path.replace(':' + key, params[key]);
});
paths.push(path);
if (i === routes.length - 1) {
link = <span>{name}</span>;
} else {
link = <Link to={path} params={params}>{name}</Link>;
link = <a href={'#' + paths.join('/')}>{name}</a>;
}
return <BreadcrumbItem separator={separator} key={name}>{link}</BreadcrumbItem>;
});

View File

@ -29,7 +29,6 @@
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|-----------|-----------------------------------|-------------------|---------|--------|
| router | 可传入 react-router 的实例 | Object | | - |
| routes | router 的路由栈信息 | Array | | - |
| params | 路由的参数 | Object | | - |
| separator | 分隔符自定义 | String or Element | | '/' |