【发布时间】: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