我目前有一个手风琴组件,尽管我需要将默认打开的第一个选项卡打开(当前默认情况下所有选项卡都关闭),但我的手风琴组件效果很好。当前,您单击“摘要”,然后通过将“详细信息”更改为“打开”来显示以下内容。我只是希望第一个孩子在默认情况下处于打开状态-并非一直处于打开状态,只是在初始加载时才打开,直到他们单击另一个选项卡为止。
以下是手风琴组件的代码:
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;
答案 0 :(得分:1)
看看这是否是您想要的。
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
};
}
然后对照open
检查index
,看看是否应该在map()
中打开当前标签页
<details
key={props.label}
open={open === index}
>
然后将open
设置为点击标签的index
this.setState({ open: index });