我正在尝试为我的网格项创建指标,因此它会将红色标记作为背景颜色。但是修改DOM似乎反应很慢,并且某些组件没有更新
这是我的代码, 我循环项目
{(function(rows, i, len) {
while (++i <= len) {
rows.push (<div
key={i.toString()}
className={"col-sm-3 bg-light mb-1 p-3 parent"}
style={that.styles.item}
onMouseEnter={that.itemMouseEnter}
onMouseLeave={that.itemMouseLeave}>
<center>
<button type="button" class="close" aria-label="Close" style={that.styles.closeButton}>
<span aria-hidden="true">×</span>
</button>
<div className="rounded-circle img-responsive mb-3" style={that.styles.image} />
<h4>VicoErv</h4>
</center>
</div>)
}
return rows;
})([], 0, 10)}
项目监听器
itemMouseEnter(event) {
event.stopPropagation();
let elem = event.target;
elem.classList.remove('bg-light');
elem.classList.add('bg-danger');
}
itemMouseLeave(event) {
event.stopPropagation();
let elem = event.target;
elem.classList.remove('bg-danger');
elem.classList.add('bg-light');
}
这里我附上gif
是否有任何解决方案可以做出反应?
答案 0 :(得分:1)
使用反应bind
和state
{(function(rows, i, len) {
while (++i <= len) {
rows.push (<div
key={i.toString()}
className={"col-sm-3 " + (that.state.itemSelected === i ? 'bg-danger' : 'bg-light') + " mb-1 p-3 parent"}
style={that.styles.item}
onMouseEnter={that.itemMouseEnter.bind(that, i)}
onMouseLeave={that.itemMouseLeave.bind(that, i)}>
<center>
<button type="button" className="close" aria-label="Close" style={that.styles.closeButton}>
<span aria-hidden="true">×</span>
</button>
<div className="rounded-circle img-responsive mb-3" style={that.styles.image} />
<h4>VicoErv</h4>
</center>
</div>)
}
return rows;
})([], 0, 10)}
事件功能
itemMouseEnter(id, e) {
e.preventDefault();
e.stopPropagation();
let elem = e.target;
this.setState({itemSelected: id})
}
itemMouseLeave(id, e) {
e.preventDefault();
let elem = e.target;
this.setState({itemSelected: false});
}