Проверьте, хотите ли вы этого.
class AccordionLight extends React.Component {
constructor() {
super();
this.state = {
open: 0
};
}
render() {
const { children, left, right } = this.props;
const { open } = this.state;
return (
<div id="accordion-light">
{children &&
children.length > 0 &&
children.map((child, index) => {
if (child.length) {
child = child[0];
}
const { props } = child;
if (props) {
return (
<details
key={props.label}
open={open === index}
>
<summary
tabIndex={0}
role="tab"
onKeyPress={e => {
e.preventDefault();
this.setState({ open: index });
}}
onClick={e => {
e.preventDefault();
this.setState({ open: index });
}}
>
<h4>{props.label}</h4>
<p>{props.sub}</p>
</summary>
{child}
</details>
);
}
return '';
})}
</div>
);
}
}
ReactDOM.render(
<AccordionLight>
<p label="one label" sub="one sub">one body</p>
<p label="two label" sub="two sub">two body</p>
<p label="three label" sub="three sub">three body</p>
<p label="four label" sub="four sub">four body</p>
</AccordionLight>,
document.getElementById('app')
);
По сути, я отслеживал, какая вкладка в данный момент открыта в состоянии, и изначально установил для нее первый дочерний элемент
constructor() {
super();
this.state = {
open: 0
};
}
* 1006. * Затем проверьте
open
против
index
, чтобы увидеть, должна ли быть открыта текущая вкладка в
map()
<details
key={props.label}
open={open === index}
>
Затем установите open
на index
выбранной вкладки
this.setState({ open: index });