作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Reactstrap/bootstrap 来实现 Accordion 功能。我的切换和 onclick 遇到问题。我的状态、功能和渲染如下所示:
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>
);
});
它会输出一个项目列表。但是,当我单击一项时,它们都会打开/切换。如何将其绑定(bind)为仅打开被单击的那个?
最佳答案
如果一次只需要展开一个元素,我建议将当前展开项目的 id
存储在您的 state
中(此处位于 >事件
)。
切换函数将接收被单击元素的 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>
);
关于reactjs - 如何将切换绑定(bind)到单击的元素以在 react 中映射数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54036117/
我是一名优秀的程序员,十分优秀!