Collapse 折叠面板的组件封装操作

144 阅读1分钟

import React, { useState, useRef,FC } from 'react';
import './panel.module.less'
import {PanelProps} from './interface'

// interface PanelProps {
//     items?: any;
//     height?: Number;
//     accordion?: boolean
// }

const Panel:FC< PanelProps> = ((props) => {
    const { items, height, accordion } = props

 
    const count = useRef<Array<HTMLDivElement | null>>([])
    const [abc, setAbc] = useState(0)

    const togglePanel = (index: any, item: any) => {

        if (!accordion) {
            if (count.current[index]?.style.height == "") {
                count.current[index]!.style.height = height + "px"
                return
            }
            if (count.current[index]?.style.height == height + "px") {
                count.current[index]!.style.height = ""
                console.log(count.current[index]?.style.height);
            }
        }if (accordion) {
            setAbc(index)
        }
    };
    return (
        <div className='zdd'>
            {
                items.map((item: any, index: any) => {
                    return (
                        <div key={item.key}>
                            <div onClick={() => togglePanel(index, item.key)} className='zd'>
                                <span>{item.label}</span>
                            </div>
                            <div className='center' ref={el => count.current[index] = el}
                                style={accordion ? { height: abc == index ? height + "px" : "0" } : undefined}
                            >
                                {item.children}
                            </div>

                        </div>

                    )
                })
            }

        </div>
    );
});



export default Panel;
import React from 'react';
import Panel from '..'
const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;
const item = [
  {
    key: '1',
    label: 'This is panel header 1',
    children: <p>{text}</p>,
  },
  {
    key: '2',
    label: 'This is panel header 2',
    children: <p>{text}</p>,
  },
  {
    key: '3',
    label: 'This is panel header 3',
    children: <p>{text}</p>,
  },
];
const App = () => <Panel   items={item} height={100} />;
export default App;