我将react与d3(新的v4)一起使用,但似乎d3缩放行为与react事件的处理方式相冲突。
我正在尝试将 mousedown 事件监听器附加到 <rect>
svg 元素。由于某种原因,当通过react附加监听器时,d3监听器会在通过react附加的监听器之前被触发。因为 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 事件组件安装后。
这不是问题,因为 D3 允许您使用 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>
);
}
}
关于javascript - React 和 d3 组合防止 mousedown 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37927563/