ant-design/components/breadcrumb/Breadcrumb.tsx

101 lines
2.7 KiB
TypeScript
Raw Normal View History

2016-09-21 11:54:53 +08:00
import React from 'react';
2016-07-14 13:29:50 +08:00
import { cloneElement } from 'react';
import warning from 'warning';
2016-03-31 17:46:35 +08:00
import BreadcrumbItem from './BreadcrumbItem';
export interface BreadcrumbProps {
prefixCls?: string;
routes?: Array<any>;
params?: Object;
separator?: string | React.ReactNode;
itemRender?: (route: any, params: any, routes: Array<any>, paths: Array<string>) => React.ReactNode;
style?: React.CSSProperties;
};
function getBreadcrumbName(route, params, routes) {
if (!route.breadcrumbName) {
2016-06-10 21:12:52 +08:00
return null;
}
2016-06-11 17:05:19 +08:00
const paramsKeys = Object.keys(params).join('|');
const name = route.breadcrumbName.replace(
2016-06-11 17:05:19 +08:00
new RegExp(`:(${paramsKeys})`, 'g'),
(replacement, key) => params[key] || replacement
);
return name;
2016-07-14 13:29:50 +08:00
}
export default class Breadcrumb extends React.Component<BreadcrumbProps, any> {
static Item: any;
2016-03-31 17:46:35 +08:00
static defaultProps = {
prefixCls: 'ant-breadcrumb',
separator: '/',
itemRender: (route, params, routes, paths) => {
const isLastItem = routes.indexOf(route) === routes.length - 1;
const name = getBreadcrumbName(route, params, routes);
return isLastItem
? <span>{name}</span>
: <a href={`#/${paths.join('/')}`}>{name}</a>;
},
2016-07-13 11:14:24 +08:00
};
2016-03-31 17:46:35 +08:00
static propTypes = {
prefixCls: React.PropTypes.string,
separator: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.element,
]),
routes: React.PropTypes.array,
params: React.PropTypes.object,
linkRender: React.PropTypes.func,
nameRender: React.PropTypes.func,
2016-07-13 11:14:24 +08:00
};
2016-03-31 17:46:35 +08:00
constructor(props) {
super();
warning(
!('linkRender' in props || 'nameRender' in props),
'`linkRender` and `nameRender` are removed, please use `itemRender` instead.'
);
}
2016-03-31 17:46:35 +08:00
render() {
let crumbs;
const { separator, prefixCls, routes, params, children, itemRender } = this.props;
2016-03-31 17:46:35 +08:00
if (routes && routes.length > 0) {
const paths = [];
crumbs = routes.map((route, i) => {
2016-04-11 11:31:35 +08:00
route.path = route.path || '';
2016-03-31 17:46:35 +08:00
let path = route.path.replace(/^\//, '');
Object.keys(params).forEach(key => {
path = path.replace(`:${key}`, params[key]);
});
if (path) {
paths.push(path);
}
if (route.breadcrumbName) {
return (
<BreadcrumbItem separator={separator} key={route.breadcrumbName}>
{itemRender(route, params, routes, paths)}
</BreadcrumbItem>
);
2016-03-31 17:46:35 +08:00
}
return null;
2016-03-31 17:46:35 +08:00
});
} else {
2016-07-14 13:29:50 +08:00
crumbs = React.Children.map(children, (element: any, index) => {
2016-03-31 17:46:35 +08:00
return cloneElement(element, {
separator,
key: index,
});
});
}
return (
<div className={prefixCls}>
{crumbs}
</div>
);
}
}