gpt4 book ai didi

reactjs - 如何将切换绑定(bind)到单击的元素以在 react 中映射数据

转载 作者:行者123 更新时间:2023-12-03 14:18:05 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com