我已经创建了一个带有react
的切换列表,当用户点击一个列表项时,它会折叠并显示一些内容。到目前为止,上帝,但现在只有当用户点击另一个列表项目时才会再次隐藏,这是好的,但我想实现我可以切换项目,我的意思是,当我点击同一项目时显示和隐藏 - >例如,我想在点击时将项目的状态设置为true / false,但我不知道该怎么做。现在我只是添加一个活动类,但是如何在一次单击时触发两个事件,即设置一个活动类并同时更改状态?
这是我到目前为止所得到的:
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>
);
}
}
答案 0 :(得分:0)
在有用的提示后想出来: - )
this.state = {
activeItem: null,
activeState: false
}
onItemActive(item) {
this.setState({activeItem: item, activeState: !this.state.activeState})
}
active={item === this.state.activeItem ? this.state.activeState : ''}
解决了!