【问题标题】:React-hooks and d3.forceSimulationReact-hooks 和 d3.forceSimulation
【发布时间】:2021-03-29 14:18:15
【问题描述】:

我在 React 中的 forceSimulation 遇到了一些问题(使用 Hooks)。问题是,每当数据发生变化时,每个气泡的位置都会被转换到屏幕中间,而不是考虑其先前的位置(参见 gif),从而使气泡以令人讨厌的方式跳跃。

我对 forceSimulation、d3 和 react-hooks 的结合没有太多经验,而且很难找到任何类似的例子;所以我非常感谢任何指导。

import React, { useEffect, useRef } from 'react'
import { forceSimulation, forceX, forceY, forceCollide, select } from 'd3'

export default function Bubbles({ data, width, height }) {
  const ref = useRef()
  const svg = select(ref.current)

  useEffect(() => {
    const simulation = forceSimulation(data)
      .force('x', forceX().strength(0.02))
      .force('y', forceY().strength(0.02))
      .force(
        'collide',
        forceCollide((d) => {
          return d.value * 20 + 3
        }).strength(0.3)
      )
    simulation.on('tick', () =>
      svg
        .selectAll('circle')
        .data(data)
        .join('circle')
        .style('fill', () => 'red')
        .attr('cx', (d) => d.x)
        .attr('cy', (d) => d.y)
        .attr('r', (d) => d.value * 20)
    )
  }, [data])

  return (
    <svg
      viewBox={`${-width / 2} ${-height / 2} ${height} ${width}`}
      width={width}
      height={height}
      ref={ref}
      style={{
        marginRight: '0px',
        marginLeft: '0px'
      }}
    ></svg>
  )
}

【问题讨论】:

  • 你是不是在点击数字时改变data?初始 x 和 y 位置是数据的一部分吗?

标签: reactjs d3.js react-hooks


【解决方案1】:

我认为这里的问题是 React 渲染 SVG,但 D3 渲染圆圈。当 React 在更新时重新渲染时,它会创建 SVG 并丢弃所有子元素,因为它不知道它们。

因此数据不能以通常的 D3 方式绑定到 DOM,而应该存储在您的 React 组件的状态中。

【讨论】:

    猜你喜欢
    • 2017-04-13
    • 2021-04-10
    • 2021-04-12
    • 2018-02-22
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2019-09-30
    • 2020-08-02
    相关资源
    最近更新 更多