Размер моего SVG обрабатывается этим компонентом: < /p>
Код: Выделить всё
import { ReactNode, useMemo } from "react";
import * as d3 from "d3";
type ChartProps = {
width: number;
height: number;
};
export const Chart = (
props: {
children?: ReactNode;
} & ChartProps,
) => {
const { children, width, height } = props;
return (
{children}
);
};
const containerRef = useRef(null);
const [sizes, setSizes] = useState({
containerWidth: initialDimension.width,
containerHeight: initialDimension.height,
});
const setContainerSize = useCallback(
(newWidth: number, newHeight: number) => {
setSizes((prevState) => {
const roundedWidth = Math.round(newWidth);
const roundedHeight = Math.round(newHeight);
if (
prevState.containerWidth === roundedWidth &&
prevState.containerHeight === roundedHeight
) {
return prevState;
}
return {
containerWidth: roundedWidth,
containerHeight: roundedHeight,
};
});
},
[],
);
useEffect(() => {
let callback = (entries: ResizeObserverEntry[]) => {
const { width: containerWidth, height: containerHeight } =
entries[0].contentRect;
setContainerSize(containerWidth, containerHeight);
};
const observer = new ResizeObserver(callback);
const { width: containerWidth, height: containerHeight } =
containerRef.current.getBoundingClientRect();
setContainerSize(containerWidth, containerHeight);
observer.observe(containerRef.current);
return () => {
observer.disconnect();
};
}, [setContainerSize]);
return (
ref={containerRef}
>
...
);
< /code>
Поэтому я думаю, что происходит то, что наблюдается, что наблюдатель Resize получает событие обновления, а затем устанавливается состояние, запуская повторный рендеринг компонента диаграммы, но из-за Способ, которым работает обновление состояния, это не происходит в том же кадре, что и обновление размер. /п>
Подробнее здесь: https://stackoverflow.com/questions/793 ... is-resized