[英]Multiple elements with the same ref, React
我有个问题。 它是:
let list = storage.map((element, index, array) => {
return (
<li key={index} className="list-element">
<div className="title-wrapper" onMouseEnter={this.handleMouseEnter}>
<p className="title">{array[index]['title']}</p>
<p className="title title-full" ref={node => this.title = node}>Text</p>
</div>
</li>
);
});
handleMouseEnter() {
this.title.style.opacity = "1";
}
因此,当鼠标进入.title-wrapper时,我想在.title-full上将不透明度设置为1。 但是,无论在哪个.title-wrapper鼠标上输入,总是将不透明度设置为最后一个.title-full。 这个问题很容易用querySelector解决,但是我读到在React中使用它是一件坏事,不是吗?
之所以将this.title
始终设置为最后一个元素,是因为this.title
循环中的每个元素都设置为this.title
,因此最后一个元素将覆盖之前的元素,依此类推。
直接使用CSS而不是完全在React中处理CSS呢? 例:
.title-wrapper:hover .title-full {
opacity: 1;
}
只是一个一般性评论,即在React中通常不推荐使用refs(有时可能是形式或模态)。 您正在模拟的是一种类似于jQuery的DOM操作方法,该方法当然可以工作,但是却回避了React基于状态,显而易见且易于遵循的功能。
我通常
this.setState({
hovered: true
})
在handleMouseEnter
方法中(并在mouseOut中取消设置)。 然后根据this.state.hovered
选择您的className
我认为使用CSS绝对是最好的方法。
对于在另一个上下文中遇到此多个引用问题的任何人,您都可以通过将引用存储在数组中来解决此问题
let list = storage.map((element, index, array) => {
return (
<li key={index} className="list-element">
<div className="title-wrapper" onMouseEnter={() => this.handleMouseEnter(index)}>
<p className="title">{array[index]['title']}</p>
<p className="title title-full" ref={node => this.titles[index] = node}>Text</p>
</div>
</li>
);
});
handleMouseEnter(index) {
this.titles[index].style.opacity = "1";
}
同样,您无需针对用例进行此操作,只是认为这可能对其他人有用:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.