[英]ReactJS How to add active class and set state to true or false on toggle list items
I've created a togglelist with react
where when the user clicks a listitem, it folds out and shows some content. 我创建了一个带有react
的切换列表,当用户单击一个列表项时,它会折叠并显示一些内容。 So far so god, but right now it only gets hidden again when the user clicks on another listitem which is ok, but I want to achieve that I can toggle an item, I mean, show and hide when I click on the same item -> eg I want to set the state of the item to true/false on click but I dont know how to do that. 到目前为止,到目前为止,但是现在仅当用户单击另一个可以的列表项时,它才再次被隐藏,但是我想实现我可以切换一个项目的意思,即当我单击同一项目时显示并隐藏- >例如,我想在单击时将项目的状态设置为true / false,但是我不知道该怎么做。 Right now I'm just adding an active class, but how to fire two events on a single click, which is to set an active class and change the state at the same time? 现在,我只是添加一个活动类,但是如何单击一次激发两个事件,即设置活动类并同时更改状态?
here is what I got so far: 这是我到目前为止所得到的:
export default class ToggleList extends React.Component{
constructor(props){
super()
this.state = {
activeItem: null
activeState: false // maybe something like this?
};
}
onItemActive(item) {
this.setState({activeItem: item})
this.setState({activeState: !this.state.activeState}) // SOMETHING LIKE THIS?
}
render() {
let itemsArray = [
"Lorem ipsum dolor?",
"consectetur adipiscing elit?",
"commodo consequat?",
"Excepteur sint occaecat?"
]
let items = itemsArray.map( (item, index) => {
return (
<ToggleListItem key={index} item={item} onItemActive={this.onItemActive.bind(this)}
active={item === this.state.activeItem} />
);
});
return(
<div className="flex-grid">
<div className="flex-grid-1">
<div className="flex-grid-header">
<h3>{this.props.title}</h3>
</div>
</div>
<div className="flex-grid-2 faq-list">
<div className="toggleList">
<ul>
{items}
</ul>
</div>
</div>
</div>
)
}
} }
class ToggleListItem extends React.Component {
constructor(props){
super()
}
setActive() {
this.props.onItemActive(this.props.item);
}
render() {
let item = this.props.item;
return (
<li className={this.props.active ? 'active' : ''} onClick={this.setActive.bind(this)} data-selected={this.props.selected}>
<div className="item-title">
<p>{item}</p>
</div>
<div className="toggle-icon-wrapper">
<div className="toggle-icon"></div>
</div>
<div className="toggleList-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam
</p>
</div>
</li>
);
}
}
Figured it out after a useful hint :-) 在一个有用的提示后想通了:-)
this.state = {
activeItem: null,
activeState: false
}
onItemActive(item) {
this.setState({activeItem: item, activeState: !this.state.activeState})
}
active={item === this.state.activeItem ? this.state.activeState : ''}
solved it! 解决了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.