我试着用D3在时间线上创建一个画笔交互,并做出react ,但我不明白为什么它不起作用.
一切看起来都很好,但是当我在useEffect()
内设置一个状态时,index
变量会创建一个无限循环.
const Timeline = () => {
const svgRef = useRef(null!);
const brushRef = useRef(null!);
const x = scaleLinear().domain([0, 1000]).range([10, 810]);
const [pos, setPos] = useState([]);
useEffect(() => {
const svg = select(svgRef.current);
svg.select('.x-axis')
.attr('transform', `translate(0,${110})`)
.call(axisBottom(x));
const brush = brushX()
.extent([
[10, 10],
[810, 110],
])
.on('start brush end', function () {
const nodeSelection = brushSelection(
select(brushRef.current).node(),
);
const index = nodeSelection.map(x.invert);
setPos(index);
});
console.log(pos);
select(brushRef.current).call(brush).call(brush.move, [0, 100].map(x));
}, [pos]);
return (
<svg ref={svgRef} width="1200" height={800}>
<rect x={x(200)} y={10} width={400} height={100} fill={'blue'} />
<g className="x-axis" />
<g ref={brushRef} />
<text>{pos[0]}-{pos[1]}</text>
</svg>
);
};
有什么办法解决这个问题吗? 谢谢!