我通过点击元素I渲染过滤器数组,将它们推送到selectedProperties
数组,并且我想在元素上设置活动类(如果它在数组中)。如何做好反应?我有下一个代码
...
render(){
const {selectedProperties} = this.state;
let classnames = classNames('box', {
'active': '' //what condition apply here to set class?
});
return (
<div className="hotel-filter">
<div className="filter-label">Что для вас важно?</div>
<div className="filter-options">
<ul className="priorities-boxes">
{
this.state.priorities.map(item => {
return (
<li key={item.id}
className={classnames}
onClick={(evt) => this.selectValue(item.id)}>
<img src={`/images/filter-icons/${item.icon}`} />
<span>{item.name}</span>
</li>
)
})
}
</ul>
</div>
</div>
)
}
我使用classnames实用程序动态添加类但我的条件错误。
答案 0 :(得分:1)
你需要引用item
以检查它是否在选定的数组中,这不能在循环外完成,否则所有都是相同的,所以只需在循环中为每个项目执行
render(){
const {selectedProperties} = this.state
return (
<div className="hotel-filter">
<div className="filter-label">Что для вас важно?</div>
<div className="filter-options">
<ul className="priorities-boxes">
{
this.state.priorities.map(item => {
return (
<li key={item.id}
className={classNames('box', {
active: selectedProperties.includes(item.id)
})}
onClick={(evt) => this.selectValue(item.id)}>
<img src={`/images/filter-icons/${item.icon}`} />
<span>{item.name}</span>
</li>
)
})
}
</ul>
</div>
</div>
)
}
答案 1 :(得分:0)
这可以解决多个元素类切换的问题。尝试一下:
https://jsfiddle.net/menomanabdulla/todu7m6g/11/
class ToggoleApp extends React.Component {
constructor(props) {
super(props)
this.state = {
}
this.toggleClass=this.toggleClass.bind(this);
}
toggleClass(e){
let classes = 'my-class';
let els = document.getElementsByClassName('my-class active');
if(els){
while (els[0]) {
els[0].classList.remove('active')
}
}
e.target.className = classes.replace('my-class','my-class active');
}
render() {
return (
<div>
<h2>Toggle Example</h2>
<ul>
<li className="my-class active" onClick={(e) =>this.toggleClass(e)}>
One
</li>
<li className="my-class" onClick={(e) =>this.toggleClass(e)}>
Two
</li>
<li className="my-class" onClick={(e) =>this.toggleClass(e)}>
Three
</li>
</ul>
</div>
)
}
}
ReactDOM.render(<ToggoleApp />, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
.my-class{
color: #FF3355;
}
.my-class.active{
color: #33FF46;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>