如何在react组件中将hover附加到svg上
目前我有图例,它显示矩形下方的文本,但我希望仅当我将鼠标悬停在矩形上时才显示文本。我尝试使用鼠标悬停和 css 悬停,但似乎没有任何效果。当我单击而不是悬停时,也会调用 mouseOver 事件。
我读了一些帖子,其中提出了这样的建议:
svg text {display: none;}
svg g:hover text {display: block;}
但目前我已经用 React 编写了这种格式的代码,那么如何将鼠标悬停到 g ?
我在下面分享了我的部分代码:
// creating svg
selectedLegend
.append("svg")
.attr("viewBox", `0 0 ${count} 1`)
.attr("preserveAspectRatio", "none")
function legend(g: any) {
// appending data
g.selectAll("g.legendCells")
.data(itemColor)
.enter()
.append("rect");
// appending text for label, which is not working as expected
g.selectAll("g")
.style("background-color", "grey")
.append("text")
.attr("class", "breakLabels")
.style("font-size", "0.4")
.attr("x", function (d: any, i: any) {
return i + "." + 25
})
.attr("y", 1.5)
.text(function (d: Record<string, unknown>, i: any) {
})
}
我尝试在 svg 和 rect 上添加这样的内容,但没有工作
.on("mouseover", function (e: any) {
// tried with this also
//select(e.target).style("display", "block")
})
小提琴: https://jsfiddle.net/s6f7z3p4/3/
注意:
<style>
svg text {display: none;}
svg g:hover text {display: block;}
</style>
如果我在小提琴中添加上面的样式,它工作正常,但是我如何在中使用上面的样式我的反应组件,因为它不支持样式标签。我在添加 :hover 到 svg(g) 时遇到问题,因为它不能作为样式添加,也不能作为 attr 添加
Currently I have legend, which display the text below the rect but I want the text to appear only when I hover over the rect. I tried using mouseover and css hover but nothing seems to work. Also mouseOver event is called when I click and not on hovering.
I read some post which suggest something like this :
svg text {display: none;}
svg g:hover text {display: block;}
But currently I have my code in this format written in react, so how to hover to the g ?
I have shared part of my code below :
// creating svg
selectedLegend
.append("svg")
.attr("viewBox", `0 0 ${count} 1`)
.attr("preserveAspectRatio", "none")
function legend(g: any) {
// appending data
g.selectAll("g.legendCells")
.data(itemColor)
.enter()
.append("rect");
// appending text for label, which is not working as expected
g.selectAll("g")
.style("background-color", "grey")
.append("text")
.attr("class", "breakLabels")
.style("font-size", "0.4")
.attr("x", function (d: any, i: any) {
return i + "." + 25
})
.attr("y", 1.5)
.text(function (d: Record<string, unknown>, i: any) {
})
}
I tried adding like this both on svg and rect but did not work
.on("mouseover", function (e: any) {
// tried with this also
//select(e.target).style("display", "block")
})
Fiddle : https://jsfiddle.net/s6f7z3p4/3/
Note:
<style>
svg text {display: none;}
svg g:hover text {display: block;}
</style>
If I add above style in fiddle it works fine but how can I use above style in my react component since it do not support style tag. I am facing issue in adding :hover to the svg(g), since it cannot be added as style or neither as attr
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论