我目前有一个手风琴组件,虽然我需要打开默认打开的第一个选项卡(当前默认情况下所有选项卡都关闭),但它仍能很好地工作。当前,您单击“摘要”,然后通过将“详细信息”更改为“打开”来显示以下内容。我只是希望第一个孩子在默认情况下处于打开状态-并非一直处于打开状态,只是在初始加载时才打开,直到他们单击另一个选项卡为止。
下面是手风琴组件的代码:
class AccordionLight extends React.Component {
constructor() {
super();
this.state = {
open: -1
};
}
render() {
const { children, left, right } = this.props;
const { open } = this.state;
return (
<div id="accordion-light">
{children &&
children.length > 0 &&
children.map(child => {
if (child.length) {
child = child[0];
}
const { props } = child;
if (props) {
return (
<details
key={props.label}
open={open && open.props && open.props.label === props.label}
>
<summary
tabIndex={0}
role="tab"
onKeyPress={e => {
e.preventDefault();
this.setState({ open: open === child ? -1 : child });
}}
onClick={e => {
e.preventDefault();
this.setState({ open: open === child ? -1 : child });
}}
>
<h4>{props.label}</h4>
<p>{props.sub}</p>
</summary>
{child}
</details>
);
}
return '';
})}
</div>
);
}
}
AccordionLight.defaultProps = {
children: null
};
AccordionLight.propTypes = {
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node])
};
export default AccordionLight;
我创建了一个代码笔-https://codepen.io/sadjaya/pen/wvByPbo。看看是否正是您想要的。基本上,我一直跟踪着哪个标签当前处于打开状态,并将其最初设置为第一个子标签
constructor() {
super();
this.state = {
open: 0
};
}
然后对照open
检查index
以查看是否应在map()
中打开当前标签页>
<details key={props.label} open={open === index} >
然后将
open
设置为单击的选项卡的index
this.setState({ open: index });