我正在使用reactstrap / bootstrap来实现手风琴功能。我在切换和点击时遇到了麻烦。我的状态,功能和渲染如下所示:
state = {
basicFeatures: [],
fuelEconomy: {},
upholsteryType: null,
category: 'Engine',
collapse: false,
active: false,
activeTab: 'capabilities',
};
toggle = active =>
this.setState({
collapse: !this.state.collapse,
active: !this.state.active,
});
const specsCatsR = this.props.specs.map((item, i) => {
return (
<React.Fragment>
<Col xs="12" key={i} className="border-bottom p-15">
<FontAwesomeIcon
icon={
this.state.active ? faMinusCircle : faPlusCircle
}
/>
<h5
className="collapse-header"
onClick={this.toggle.bind(this)}
>
{' '}
{item.category}{' '}
</h5>
<Collapse isOpen={this.state.active}>
<SpecsDetails
vehicle={this.props.vehicle}
values={item.values}
category={item.category}
/>
</Collapse>
</Col>
</React.Fragment>
);
});
它弹出一个项目列表。但是,当我单击一项时,它们全部打开/切换。如何将其绑定为仅打开被单击的那个?
答案 0 :(得分:2)
如果一次只能扩展您的一个元素,建议您将当前扩展项的id
存储在state
(此处为active
)中。< br />
切换功能将通过对其进行预配置来接收被单击元素的id
和onClick
事件参数:
state = {
basicFeatures: [],
fuelEconomy: {},
upholsteryType: null,
category: 'Engine',
collapse: false,
active: null, //Active is not a boolean anymore
activeTab: 'capabilities',
};
toggle = id => ev => { //Add brackets here, you do not need to return the result of setState
this.setState({
collapse: !this.state.collapse,
active: id,
});
}
const specsCatsR = this.props.specs.map((item, i) =>
<React.Fragment>
<Col xs="12" key={i} className="border-bottom p-15">
<FontAwesomeIcon
icon={
this.state.active ? faMinusCircle : faPlusCircle
}
/>
<h5
className="collapse-header"
onClick={this.toggle(i)} // bind is not necessary since you are using an arrow function
>
{` ${item.category} `}
</h5>
<Collapse isOpen={this.state.active === i}> //If the index is the same as the active element id, it expands
<SpecsDetails
vehicle={this.props.vehicle}
values={item.values}
category={item.category}
/>
</Collapse>
</Col>
</React.Fragment>
);