- React Material:UI Cookbook
- Adam Boduch
- 260字
- 2021-06-24 15:49:38
There's more...
You can also use state to control whether or not a panel is expanded. For example, you can use ExpansionPanel components to create an accordion widget—there's always one panel open, and opening another panel closes anything that's open.
The first step is to add an expanded state to determine which panel is open at any given time:
const [expanded, setExpanded] = useState(0);
const [panels] = useState([
{
title: 'First Panel Title',
content: 'First panel content...'
},
{
title: 'Second Panel Title',
content: 'Second panel content...'
},
{
title: 'Third Panel Title',
content: 'Third panel content...'
},
{
title: 'Fourth Panel Title',
content: 'Fourth panel content...'
}
]);
The expanded state defaults to 0, meaning that the first panel is expanded by default. As the expanded panels change, the expanded state changes to reflect the index of the expanded panel. Next, you'll add an onChange handler for the ExpansionPanel component:
const onChange = expanded => () => {
setExpanded(expanded);
};
This is a higher-order function—it takes the index of the panel you want to expand and returns a function that sets the expanded state when the given panel is clicked on. Finally, you can add the new expanded state and the onChange handler to the ExpansionPanel component:
<ExpansionPanel
key={index}
expanded={index === expanded}
disabled={panel.disabled}
onChange={onChange(index)}
>
<ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}>
<Typography>{panel.title}</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>{panel.content}</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
The expanded property is based on the index of the current panel, equaling the expanded state of your component. If they're equal, the panel is expanded. The onChange handler is also assigned to ExpansionPanel, which changes the expanded state when the panel is clicked on.