[英]React & d3 combination prevents mousedown event
我正在使用與d3(新的v4)一起反應,但似乎d3縮放行為與反應事件的處理方式相沖突。
我正在嘗試將mousedown事件偵聽器附加到<rect>
svg元素。 出於某種原因,當通過react連接偵聽器時,在偵聽器附加的反應之前觸發d3偵聽器。 因為d3停止任何進一步的傳播,所以我的監聽器永遠不會被調用。
但是當我通過純javascript直接附加監聽器或禁用縮放行為時,它可以工作。
class Rectangle extends React.Component {
componentDidMount() {
// get main d3 selector
this.canvas = d3.select('#react-root svg');
// init the pan & zoom behaviour
this.zoom = d3.zoom()
.on('start', () => {
console.log('zoom started!');
})
.on('zoom', () => {
console.log('zooming!');
});
this.canvas.call(this.zoom);
document.addEventListener('mousedown', () => {
console.log("window mousedown!");
});
document.querySelector('#react-root svg rect').addEventListener('mousedown', () => {
console.log('rect mousedown! (via pure js)');
});
}
render() {
return (
<svg onMouseDown={() => console.log('svg mousedown! (via react)')}>
<rect
rx="10" ry="10"
width="100" height="100"
onMouseDown={() => console.log('rect mousedown! (via react)')}
onTouchStart={() => console.log('touch down!')}
/>
</svg>
);
}
}
ReactDOM.render(<Rectangle />, document.getElementById('react-root'));
有什么建議么? 謝謝!
我猜D3是在組件安裝后從<rect>
刪除你的React Events。
這不是問題,因為D3允許您使用type.name
為同一事件注冊多個偵聽type.name
。
例如: start.native
& start.react
。
如何將此應用於您的代碼? 像這樣
class Rectangle extends React.Component {
componentDidMount() {
this.canvas = d3.select('#react-root svg');
this.zoom = d3.zoom()
.on('start.native', () => {
console.log('mouse down using pure js');
})
.on('end.native', () => {
console.log('mouse up using pure js');
})
.on('start.react',this.onMouseDownWithReact)
.on('end.react', this.onMouseUpWithReact);
this.canvas.call(this.zoom);
}
onMouseDownWithReact(){
console.log("Mouse Down with react");
}
onMouseUpWithReact(){
console.log("Mouse Up with react");
}
render() {
return (
<svg onMouseDown={() => console.log('svg mousedown! (via react)')}>
<rect
rx="10" ry="10"
width="100" height="100"
/>
</svg>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.