【发布时间】:2017-11-01 07:09:37
【问题描述】:
我正在使用 React-Photon 套件创建前端,虽然它非常棒,但它确实为我带来了一些未知数。
具体来说,我有一个侧边栏导航<Photon.NavGroup>,它会在更改时动态绘制顶部导航栏。这通过 Redux / Thunk 运行良好,依赖于 index 值。当 onClick 到 NavGroupItem 发生时,调度会更新存储,并且所有内容都会根据需要重新呈现。
我在顶部导航中添加了一个持久的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);
【问题讨论】:
标签: javascript reactjs redux jsx