javascript - React 和 d3 组合防止 mousedown 事件

标签 javascript reactjs d3.js

我将react与d3(新的v4)一起使用,但似乎d3缩放行为与react事件的处理方式相冲突。

我正在尝试将 mousedown 事件监听器附加到 <rect> svg 元素。由于某种原因,当通过react附加监听器时,d3监听器会在通过react附加的监听器之前被触发。因为 d3 停止任何进一步的传播,所以我的监听器永远不会被调用。

但是当我直接通过纯 JavaScript 附加监听器或禁用缩放行为时,它会起作用。

See this example on codepen

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/

相关文章:

javascript - 如何在从 Meteor.method 返回之前等待子进程结果

javascript - 在 Javascript 中检测 HTML <a> 点击通话支持

reactjs - 无法从 "./utils/batch"解析 "node_modules\react-redux\lib\index.js"

javascript - React Native - 需要循环

javascript - Google Maps API 更改了我的字体系列

javascript - 单击另一个缩略图更改图像

javascript - 将外部 jsx 文件添加到 html 页面( react )

javascript - React 中的动画 SVG 弧形路径

javascript - 过渡圆弧时出错 : <path> attribute d: Expected arc flag ('0' or '1' )

javascript - 在 <svg> 容器中通过 d3 实现 <div> 工具提示