需求背景
效果图:
由于不确定手风琴的个数,所以无法通过一个全局的state.hidden属性统一设置。
有两种解决方法:
1. 数组的方式
2. 建立索引值查找(本文所使用的方法)
import React,{ Component } from 'react';
import styles from './List.css';
import { connect } from 'react-redux';
import { loadList } from '../../actions';
@connect(
(state,ownProps) => {
const selectedMenu = ownProps.location.hash.split('#')[1]; //获取URL中的hash值
return {
selectedMenu,}
},{ loadList }
)
class List extends Component {
constructor(props) {
super(props);
this.renderSection = this.renderSection.bind(this);
}
//控制是否展开二级标题
handleSubTitleShow = (evt) => {
const node = evt.currentTarget;
const idx = node.dataset.idx;
const { history,location,selectedMenu } = this.props;
//如果双击一级标题,清空hash值,收起当前的二级标题。否则认为是单击,展开二级标题
if (selectedMenu === idx) {
history.replace({
...location,hash: '',});
}
else {
history.replace({
...location,hash: idx,});
}
}
//二级标题
renderSectionRow(item,idx) {
const { name } = item;
return (
<div className={styles.sectionContentRow} key={`secRow${idx}`}>Q{idx+1}:{name}</div>
);
}
//一级标题
renderSection(item,idx) {
const key = '' + idx; //由于从URL获取的hash值是字符串,所以把idx也改为字符串,方便后面做对比
const { selectedMenu } = this.props;
const { name,articleVoList } = item;
return (
<div className={styles.section} key={key}>
<a data-idx={key} className={styles.secTitle} onClick={this.handleSubTitleShow}>
<span>{name}</span>
<span className={selectedMenu === key ? styles.secTitleIconCurrent : styles.secTitleIcon}> </span>
</a>
{selectedMenu === key && articleVoList.map(this.renderSectionRow)}
</div>
);
}
render() {
const { list } = this.props;
if (!list) {
return null;
}
return (
<div className={styles.wrapper}>
{list.map(this.renderSection)}
</div>
);
}
}
export default List;
Author:致知 Sign:路漫漫其修远兮,吾将上下而求索。