【React】React实现手风琴效果

需求背景

效果图:



由于不确定手风琴的个数,所以无法通过一个全局的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:路漫漫其修远兮,吾将上下而求索。

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...