gpt4 book ai didi

javascript - React onMouseEnter/onMouseLeave 没有按预期工作(奇怪的行为)

转载 作者:行者123 更新时间:2023-12-03 02:19:26 27 4
gpt4 key购买 nike

我正在尝试为我的网格项目创建指示器,因此它将给出红色标记作为背景颜色。但修改 DOM 时 react 似乎很慢,并且导致某些组件未更新

这是我的代码,我循环该项目

{(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">&times;</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

react strange

有什么解决方案可以在 react 中做到这一点吗?

最佳答案

通过使用react bindstate解决

{(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">&times;</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});
}

关于javascript - React onMouseEnter/onMouseLeave 没有按预期工作(奇怪的行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49228471/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com