我试图弄清楚如何在ReactJs的按钮组上切换“活动”类。我试图避免在这里使用JQuery并试图弄清楚如何用React实现它。任何帮助,不胜感激。代码:
class TimelineNav extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
return(
<div className="TimelineNav">
<button href="#" className="allFilter active">All</button>
<button href="#" className="professionalFilter">Professional</button>
<button href="#" className="academicFilter">Academic</button>
<button href="#" className="miscFilter">Miscellaneous</button>
</div>
)
}
}
最佳答案
尽管有一些方法可以使这种方法更高效/更优雅,但这是一种实现方法
class TimelineNav extends React.Component {
constructor() {
super();
this.state = {
'active': 0
};
}
setActive( index ) {
this.setState({ 'active': index });
}
render() {
var current = this.state.active;
var getClass = function( name, index ) {
if ( index === current )
return name + ' active';
return name;
};
return(
<div className="TimelineNav">
<button href="#" onClick={this.setActive.bind(this, 0)} className={getClass("allFilter",0)}>All</button>
<button href="#" onClick={this.setActive.bind(this, 1)} className={getClass("professionalFilter",1)}>Professional</button>
<button href="#" onClick={this.setActive.bind(this, 2)} className={getClass("academicFilter",2)}>Academic</button>
<button href="#" onClick={this.setActive.bind(this, 3)} className={getClass("miscFilter",3)}>Miscellaneous</button>
</div>
)
}
}