30行代碼-React使用hook手寫手風琴

1. 先給儂們看下效果哈


2. 開始準備擼代碼了

2.1 準備數據

const data = [
    { title: '春天', content: '竹外桃花三兩枝,春江水暖鴨先知。', author: '蘇軾', name: '《惠崇春江晚景 》' },
    { title: '夏天', content: '小荷才露尖尖角,早有蜻蜓立上頭。', author: '楊萬里', name: '《小池》' },
    { title: '秋天', content: '人生若只如初見,何事秋風悲畫扇。', author: '納蘭性德', name: '《木蘭詞·擬古決絕詞柬友》' },
    { title: '冬天', content: '朔風如解意,容易莫摧殘。', author: '崔道融', name: '《梅花》' },
]


複製代碼

2.2開始擼代碼,快看一部當心就沒了

import React, { Component, useState, useEffect } from 'react'
import './index.css'
const AccordionItem = (props) => {
    const [heightItem, setHeightItem] = useState(0)
    useEffect(() => {
        setHeightItem(props.visable ?
            document.getElementById(`item_${props.index}`).scrollHeight
            : 0)
    })
    const { item, index, setVisable } = props
    return (
        <div className='accordion-item' onClick={() => setVisable(index)} >
            <div className='title'>{item.title}</div>
            <div className='content-box' style={{ height: heightItem }}
                id={`item_${index}`}>
                <p>{item.content}</p>
                <p>--{item.author}{item.name}</p>
            </div>
        </div>
    );
}
const Accordion = () => {
    const [visable, setVisable] = useState([true, false, false, false])
    const setVisableChild = (key) => {
        setVisable(visable.map((one, index) => key == index ? true : false))
    }
    return <div className='accordion'>
        {data.map((item, index) => {
            return <AccordionItem item={item} key={index} index={index}
                visable={visable[index]} setVisable={setVisableChild}
            />
        })}
    </div>
}
export default Accordion;


複製代碼

2.3 樣式搞上

.accordion {
    width: 500px;
    margin: 0px auto;
    border: 1px solid #ccc;
}

.title {
    padding: 10px;
    font-size: 20px;
    font-weight: bold;
    background: #ccc;
    border-top: 1px solid #fff;
}

.content-box {
    background: rgb(250, 245, 245);
    padding: 0px 10px;
    overflow: hidden;
    height: 0px;
    transition: .5s;
}

.content-box p:last-child {
    text-align: right;
}


複製代碼

2.4 收工👏👏👏👏👏👏👏👏👏👏👏👏

相關文章
相關標籤/搜索