我到處尋找試圖弄清楚這一點。我有一個基本的 svg 元素,里面有一個路徑元素。我無能為力,不會觸發 onClick 函式。如果將 handleClick 傳遞給 div,它將觸發,但我需要能夠在特定路徑上觸發 onClick 事件。
const handleClick = () => {
alert('clicked')
}
return (
<div className="bg-blue-400">
<svg viewBox={`0 0 ${props.size[0]} ${props.size[1]}`} onClick={() => handleClick()}>
<g>
<path
d={outline}
stroke="black"
fill="aliceblue"
strokeWidth={0.5}
strokeDasharray="10,10"
onClick={() => alert('path was clicked')}
/>
</g>
</svg>
</div>
)
任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
我充實了您的代碼并outline從在線示例中定義,它作業正常。當我單擊此繪制的心形時,會顯示“已單擊路徑”警報,當我單擊“確定”以關閉它時,“已單擊”警報似乎已在其后面,所以我猜這是首先觸發的?
import React from 'react';
const Comp = (props) => {
const handleClick = () => {
alert('clicked')
}
const outline = `M 10,30
A 20,20 0,0,1 50,30
A 20,20 0,0,1 90,30
Q 90,60 50,90
Q 10,60 10,30 z`;
return (
<div className="bg-blue-400">
<svg viewBox={`0 0 ${props.size[0]} ${props.size[1]}`} onClick={() => handleClick()}>
<g>
<path
d={outline}
stroke="black"
fill="aliceblue"
strokeWidth={0.5}
strokeDasharray="10,10"
onClick={() => alert('path was clicked')}
/>
</g>
</svg>
</div>
)}
export const App = () => {
return(<div>
<Comp size={[400, 400]}/>
</div>)
}
export default App;
定義了一個css檔案
.bg-blue-400 {
background-color: blue;
}
我唯一能想象到的是導致你的問題可能是如何outline定義的,或者尺寸道具?
uj5u.com熱心網友回復:
到目前為止,我所做的一切似乎都沒有奏效。然后我嘗試使用另一種方法,我使用 d3 和 useRef 來顯示 svg 并添加指標事件,到目前為止這似乎已經奏效。
const svgRef = useRef(null)
const [height, width] = props.size;
useEffect(() => {
//accesses the reference element
const svg = d3.select(svgRef.current)
//declares the geoJson, projection, and path(pathGenerator)
const geoJson = props.GeoJson
const projection = props.projectionType()
.fitSize(props.size, geoGraticule10())
.translate(props.translate)
const path = d3.geoPath().projection(projection)
//uses d3 to inject the data into the svg element
const features = svg.selectAll(".country")
.data(geoJson ? geoJson.features : [])
.enter().append("path")
//basic styling attributes
.attr("d", path)
.attr("fill", "none")
.attr("stroke", "aliceblue")
.attr("stroke-width", "0.5px")
//allows pointer events anywhere inside the path even when fill=none
.attr("pointer-events", "visibleFill")
.attr("visibility", "visible")
//sets the path element id to the continent name
.attr("id", (d) => {
return `${d.properties.continent}`
})
//selects the current continent and highlights it by increasing the stroke width
.on("mouseover", (d,i) => {
svg.select(`#${i.properties.continent}`).attr("stroke-width", "2px")
})
//deselects
.on("mouseleave", (d,i) => {
svg.select(`#${i.properties.continent}`).attr("stroke-width", "0.5px")
})
//adds the .country attribute to allow for later updates on the svg element
.attr("class", "country")
}, [geoJson]);
return (
<div className="bg-blue-400">
<svg ref={svgRef} viewBox={`0 0 ${props.size[0]} ${props.size[1]}`} />
</div>
)
}
export default TestMap
這適用于不同的 json 檔案,但適用于原始路徑
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454217.html
