--- title: Accordion tags: visual,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 `props.children`. - Each `AccordionItem` component renders a `
{props.children}
); } function Accordion(props) { const [bindIndex, setBindIndex] = React.useState(props.defaultIndex); const changeItem = itemIndex => { if (typeof props.onItemClick === 'function') props.onItemClick(itemIndex); if (itemIndex !== bindIndex) setBindIndex(itemIndex); }; const items = props.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') ); ```