[英]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.