【问题标题】:d3 js drag event listener isnt getting the event - (d3, react)d3 js拖动事件侦听器没有收到事件-(d3,反应)
【发布时间】:2022-01-16 00:06:49
【问题描述】:

我正在尝试将拖动事件添加到我的 d3 强制布局中,但由于某种原因,未定义事件 attr,因此没有任何反应。我知道 d3-drag 的新文档发生了变化,我按照这些说明进行操作。

这是我的代码:

    const node = svg
      .selectAll("circle")
      .data(nodes)
      .enter()
      .append("circle")
      .attr("r", 35) // radius field, so width and height 80X80
      .attr("stroke", "lightgray")
      .attr("stroke-width", 0.5)
      .style("fill", "lightgray")
      .call(handler
      .on('start', dragstarted)
      .on('drag', dragged)
      .on('end', dragended)

事件函数:

    const dragstarted = (event: any, d: any) => {
      console.log(' dragged d', d);
      console.log('event', event);

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (!event.active) {
        simulation.alphaTarget(0.3).restart();
      }
      d.fx = d.x;
      d.fy = d.y;
    }

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const dragged = (event: any, d: any) => {
      console.log(' dragged d', d);
      console.log('event', event);

      d.fx = event.x;
      d.fy = event.y;
    }

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const dragended = (event: any, d: any) => {
      console.log(' dragended  d', d);
      console.log('event', event);

      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (event.active) {
        simulation.alphaTarget(0);
      }

      d.fx = null;
      d.fy = null;
    }

文档中的示例:

  d3.drag()
       .on("start", (event, d) => circle.filter(p => p === d).raise().attr("stroke", "black"))
       .on("drag", (event, d) => (d.x = event.x, d.y = event.y))
       .on("end", (event, d) => circle.filter(p => p === d).attr("stroke", null))

这就是我得到的:

Uncaught TypeError: Cannot read properties of undefined (reading 'document')
    at nodrag.js:5

我为未能获得事件的地方添加了屏幕截图

我不明白我在这里做错了什么,感谢您的帮助。

编辑 完整的代码示例: https://stackblitz.com/edit/react-saqrv9?file=src%2Fgraph.tsx

【问题讨论】:

标签: javascript reactjs d3.js


【解决方案1】:

请注意,新 API 未使用 d3.event,而是将事件传递给事件侦听器。

为感兴趣的人更新了 sn-p,我知道那里没有很多例子,所以玩得开心

https://stackblitz.com/edit/react-saqrv9?file=src%2Fgraph.tsx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多