← Wszystkie zadaniaReact · Middle
Akordeon
Napisz komponent Accordion, który dostaje tablicę items z obiektów { title, content }. Każda pozycja ma przycisk z tekstem title, a pod nim content, gdy pozycja jest otwarta.
Na początku wszystkie pozycje są zamknięte. Naraz otwarta jest tylko jedna: otwarcie pozycji zamyka inną, a ponowne kliknięcie zamyka bieżącą. Przycisk ma aria-expanded ze stanem pozycji.
Ctrl+Enter uruchamia testy. Tab robi wcięcie; aby wyjść z edytora klawiaturą, naciśnij Esc, a potem Tab. Kod zapisuje się w tej przeglądarce.
Testy (4)
const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }]; render(<Accordion items={items} />); expect(screen.queryByText('A1')).toBe(null); expect(screen.queryByText('A2')).toBe(null); expect(screen.getByRole('button', { name: 'Q1' }).getAttribute('aria-expanded')).toBe('false');
const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }]; render(<Accordion items={items} />); fireEvent.click(screen.getByRole('button', { name: 'Q1' })); expect(screen.getByText('A1')).toBeTruthy(); expect(screen.getByRole('button', { name: 'Q1' }).getAttribute('aria-expanded')).toBe('true');
const items = [{ title: 'Q1', content: 'A1' }, { title: 'Q2', content: 'A2' }]; render(<Accordion items={items} />); fireEvent.click(screen.getByRole('button', { name: 'Q1' })); fireEvent.click(screen.getByRole('button', { name: 'Q2' })); expect(screen.getByText('A2')).toBeTruthy(); expect(screen.queryByText('A1')).toBe(null);
const items = [{ title: 'Q1', content: 'A1' }]; render(<Accordion items={items} />); fireEvent.click(screen.getByRole('button', { name: 'Q1' })); fireEvent.click(screen.getByRole('button', { name: 'Q1' })); expect(screen.queryByText('A1')).toBe(null);