0
我想構建一個動態NavBar組件,從React路由呈現,我接收路由作爲道具,然後構建一個數組作爲導航組件呈現,但html並不是渲染React JS渲染列表後
下面是代碼
import React from 'react';
import { Link } from 'react-router';
class NavBarComponent extends React.Component {
constructor() {
super();
this.routeList = [];
}
_getDisplayName(route) {
let name = null;
if (typeof route.getDisplayName === 'function') {
name = route.getDisplayName();
}
if (route.indexRoute) {
name = name || route.indexRoute.displayName || null;
} else {
name = name || route.displayName || null;
}
//check to see if a custom name has been applied to the route
if (!name && !!route.name) {
name = route.name;
}
//if the name exists and it's in the excludes list exclude this route
//if (name && this.props.excludes.some(item => item === name)) return null;
if (!name) {
name = "";
}
return name;
}
_checkAddRoutes(route, isRoot) {
let name = this._getDisplayName(route);
let exist = this.routeList.find(y => y.path === route.path);
if (exist == null && name && route.path) {
if (!isRoot) {
name = '/' + name;
}
this.routeList.push({ "path": route.path, "name": name });
}
}
_buildRoutes(routes) {
routes.forEach((_route) => {
let isRoot = routes[1] && !routes[1].hasOwnProperty("path");
let route = Object.assign({}, _route);
if (typeof _route.prettifyParam === 'function') {
route.prettifyParam = _route.prettifyParam;
}
if (isRoot && !route.path) {
route.path = '/';
}
this._checkAddRoutes(route, isRoot);
if (isRoot && route.childRoutes && route.childRoutes.length) {
let cls = this;
route.childRoutes.forEach(chilRoute => {
cls._checkAddRoutes(chilRoute);
});
}
});
}
renderListItem(item) {
return <li> <Link to="/about" activeClassName="sui-active">{item.name}</Link> </li>;
}
renderList() {
if (this.routeList && this.routeList.length) {
return this.routeList.map(item => this.renderListItem(item));
}
return [];
}
render() {
this._buildRoutes(this.props.routes);
return (
<ul className="sui-navbar sui-border sui-round">
{this.renderList}
</ul>
);
}
}
NavBarComponent.propTypes = {
routes: React.PropTypes.arrayOf(React.PropTypes.object).isRequired
};
module.exports = NavBarComponent;