单击列表中的项目时,我正在尝试添加活动类。单击第二项后,从第一项中删除课程,然后将其添加到第二项。
到目前为止,我有此代码:
constructor(props) {
super(props)
this.state = {
clicked: false,
showComponent: "Box1"
};
}
addClassName = () => {
this.setState({
clicked: true
});
}
<ul>
<li className = {
this.state.clicked ? 'active' : 'inactive'
}
onClick = {() => {
this.toggleDiv("monday");
this.addClassName();
}
} data-sched = "monday"> Monday </li>
<li className = {
this.state.clicked ? 'active' : 'inactive'
}
onClick = {() => {
this.toggleDiv("thursday");
this.addClassName();
}
}
data-sched = "tuesday" > Thursday </li>
</ul>
问题是当我单击活动的第一项类别时(第一项和第二项)。
答案 0 :(得分:1)
当点击状态为true时,两个li标签具有相同的类,因为这两个条件都为true。试试这个。
constructor(props) {
super(props)
this.state = {
clicked: false,
active:'',
showComponent: "Box1"
};
}
<ul>
<li className = {
this.state.active=='monday' ? 'active' : 'inactive'
}
onClick = {() => {
this.toggleDiv("monday");
this.setState({active:'monday'})
}
} data-sched = "monday">
Monday
</li>
<li className = {
this.state.active:'thursday'? 'active' : 'inactive'
}
onClick = {() => {
this.toggleDiv("thursday");
this.setState({active:'thursday'})
}
}
data-sched = "thursday" >
Thursday
</li>
</ul>
答案 1 :(得分:0)
您必须保存单击的值:
constructor(props) {
super(props)
this.state = {
selectedDay: null,
showComponent: "Box1"
};
}
然后直接使用它(也删除了一些重复的代码)。
selectDay = day => {
this.toggleDiv(day);
this.setState({
selectedDay: day
});
}
render() {
...
const days = [
{ name: 'monday', label: 'Monday' },
{ name: 'thursday', label: 'Thursday' }
];
return (
<ul>
{days.map(day => (
<li
key={day.name}
className={this.state.selectedDay === day.name ? 'active' : 'inactive'}
onClick={() => this.selectDay(day.name)}
data-sched={day.name}
>
{day.label}
</li>
)}
</ul>
);
}