React / Redux 从非相关组件中删除 'active'

React / Redux remove 'active' from non-related component

我正在使用 React-Photon 套件创建一个前端,虽然它很棒,但它确实给我带来了一些未知数。

具体来说,我有一个侧边栏导航 <Photon.NavGroup> 可以在更改时动态绘制顶部导航栏。这通过 Redux / Thunk 并且运行良好,依赖于 index 值。当 onClickNavGroupItem 发生时,调度会更新商店并根据需要重新呈现所有内容。

我在顶部导航栏中添加了一个固定的 Home 按钮,它与边栏无关。它从 onClick 调度一个 index:0,这会导致加载所需的主页并通过更新商店重置顶部导航。

我难以理解的是更新(删除)当前选定的 NavGroupItem 的 class = 'active'

的适当方法

我看过很多文章,但它们都涉及现有的父/子关系。在这种情况下不存在(表亲?)

我可能会在 React 之外将其作为...

const els: any = document.getElementsByClassName('active');
  if (els != null) {
    [...els].forEach(el => {
      el.getAttribute('class').replace('active', '');
    });
  }

但我想留在框架内。

我的边栏看起来像:

// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import * as Photon from '../vendor/photon';

/** Thunk actions */
import updateSidebar from '../actions/sidebar-actions';

/** Action Type Constant */
import { UPDATE_SIDEBAR_INDEX } from '../constants/ActionTypes';

class Sidebar extends Component {
  onSelect: Function
  state: {
    index: number
  }

  action: {
    type: string,
    index: number
  }

  constructor(props: Object) {
    super(props);
    this.onSelect = this.onSelect.bind(this);
    this.state = {
      index: 0
    };
  }

  onSelect(index: number) {
    this.setState(() => ({
      index
    }));

    const setNav = () => {
      switch (index) {
        case 1:
          return '/Dashboard';
        case 2:
          return '/Logistics';
        case 3:
          return '/Operations';
        case 4:
          return '/Reporting';
        case 5:
          return '/Transactions';
        default:
          return null;
      }
    };

    this.action = {
      type: UPDATE_SIDEBAR_INDEX,
      index
    };
    this.props.updateSidebar(UPDATE_SIDEBAR_INDEX, this.state, this.action);
    this.props.navigateTo(setNav());
  }

  render() {
    return (
      <Photon.Pane ptSize="sm" sidebar>
        <Photon.NavGroup onSelect={this.onSelect.bind(this)} >
          <Photon.NavGroupItem eventKey={1} glyph="gauge" text="Dashboard" />
          <Photon.NavGroupItem eventKey={2} glyph="globe" text="Logistics" />
          <Photon.NavGroupItem eventKey={3} glyph="cog" text="Operations" />
          <Photon.NavGroupItem eventKey={4} glyph="print" text="Reporting" />
          <Photon.NavGroupItem eventKey={5} glyph="publish" text="Transactions" />
        </Photon.NavGroup>
      </Photon.Pane >
    );
  }
}

const mapDispatchToProps = (dispatch: *) => ({
  updateSidebar: (type, state, action) => dispatch(updateSidebar(type, state, action)),
  navigateTo: (path: string) => dispatch(push(path))
});

export default connect(null, mapDispatchToProps)(Sidebar);

使用这个:

[...els].forEach(el => {
  el.classList.remove('active');
});

注意:这不适用于 IE<10,您可以使用 jquery 并使用 $(el).removeClass('active')