我目前有一个 Accordion 组件运行良好,但我需要第一个选项卡默认打开(当前所有选项卡默认关闭)。当前您单击“摘要”,它会通过将“详细信息”更改为“打开”为真来显示以下内容。我只是希望第一个 child 默认打开 - 不总是打开,只是在初始加载时打开,直到他们单击另一个选项卡。
下面是 Accordion 组件的代码:
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;
最佳答案
看看这是不是你想要的。
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')
);
基本上我一直在跟踪哪个选项卡当前处于打开状态,并最初将其设置为第一个 child
constructor() {
super();
this.state = {
open: 0
};
}
然后检查 open
与 index
是否应该在 map()
中打开当前选项卡
<details
key={props.label}
open={open === index}
>
然后将open
设置为点击标签的index
this.setState({ open: index });
关于reactjs - 如何使 Accordion 默认打开第一个选项卡 React JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638937/