index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import React, { Component } from 'react';
  2. import * as _ from 'lodash';
  3. import { Nav } from '../../../index';
  4. const navList = [
  5. {
  6. path: 'components',
  7. title: '所有组件',
  8. },
  9. {
  10. path: 'demo',
  11. title: '主题样例',
  12. children: [
  13. {
  14. path: 'demo_workstation',
  15. title: '工作台',
  16. },
  17. ],
  18. },
  19. ];
  20. const searchToJson = (search = '') => {
  21. const pairs = search.substring(1).split('&');
  22. const obj = {};
  23. let pair;
  24. let i;
  25. for (i in pairs) {
  26. if (pairs[i] === '') continue;
  27. pair = pairs[i].split('=');
  28. obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  29. }
  30. return obj;
  31. };
  32. const jsonToSearch = (json = {}) => {
  33. return Object.entries(json)
  34. .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  35. .join('&');
  36. };
  37. export class Navbar extends Component {
  38. static defaultProps = {
  39. notifyNavChange: path => {
  40. const json = searchToJson(window.location.search);
  41. json.itemKey = path;
  42. window.location.search = jsonToSearch(json);
  43. },
  44. };
  45. constructor(props) {
  46. super(props);
  47. this.state = {
  48. selectedKeys: ['components'],
  49. };
  50. }
  51. componentDidMount() {
  52. this.setKey();
  53. }
  54. componentDidUpdate() {
  55. this.setKey();
  56. }
  57. setKey(key) {
  58. // const pathname = window.location.hash;
  59. key = key || searchToJson()['itemKey'];
  60. const { selectedKeys } = this.state;
  61. if (key && key !== selectedKeys[0]) {
  62. this.setState({ selectedKeys: [key] });
  63. }
  64. }
  65. setActive = (key, path) => {
  66. if (key !== this.state.selectedKeys[0]) {
  67. // 通知父组件变更路由,之后会触发didUpdate
  68. this.props.notifyNavChange(path);
  69. this.setState({});
  70. }
  71. };
  72. renderNavItem = config => {
  73. const { path, title, children } = config;
  74. let props = {
  75. itemKey: path,
  76. text: title,
  77. key: path,
  78. };
  79. if (children) {
  80. return <Nav.Sub {...props}>{children.map(sub => this.renderNavItem(sub))}</Nav.Sub>;
  81. }
  82. return <Nav.Item {...props} onClick={() => this.setActive(path, path)} />;
  83. };
  84. render() {
  85. let { selectedKeys } = this.state;
  86. return (
  87. <Nav className="page-nav" defaultOpenKeys={[navList[1].path]} selectedKeys={selectedKeys}>
  88. {navList.map(item => this.renderNavItem(item))}
  89. <Nav.Footer collapseButton={true} />
  90. </Nav>
  91. );
  92. }
  93. }
  94. export default Navbar;