--- title: Accordion tags: components,children,state,advanced --- Renders an accordion menu with multiple collapsible content components. - Define an `AccordionItem` component, pass it to the `Accordion` and remove unnecessary nodes expect for `AccordionItem` by identifying the function's name in `children`. - Each `AccordionItem` component renders a `
{children}
); }; const Accordion = ({ defaultIndex, onItemClick, children }) => { const [bindIndex, setBindIndex] = React.useState(defaultIndex); const changeItem = itemIndex => { if (typeof onItemClick === 'function') onItemClick(itemIndex); if (itemIndex !== bindIndex) setBindIndex(itemIndex); }; const items = children.filter(item => item.type.name === 'AccordionItem'); return (
{items.map(({ props }) => ( changeItem(props.index)} children={props.children} /> ))}
); }; ``` ```jsx ReactDOM.render( Lorem ipsum Dolor sit amet , document.getElementById('root') ); ```