1

我在 React 中有以下 useEffect 调用:

const containerRef = useRef(null);

useEffect(() => {
    function handleResize() {
        const {offsetWidth} = containerRef.current;
        setWidth(offsetWidth);
        console.log(width);
    }
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
}, [containerRef, width]);

我要做的是获取包装胜利图表的 div 的宽度并将其传递给图表,以便它可以调整其纵横比以启用具有固定高度的灵活宽度:

<div ref={containerRef}>
                            <VictoryChart theme={DataVizTheme} width={width} height={250} containerComponent={<VictoryContainer responsive={false} />}>
                                <VictoryAxis
                                    tickValues={[1, 2, 3, 4, 5, 6, 7]}
                                    tickFormat={["Mon 7", "Tue 8", "Wed 9", "Thu 10", "Fri 11", "Sat 12", "Sun 13"]}
                                />
                                <VictoryAxis
                                    dependentAxis
                                />
                                <VictoryStack>
                                    <VictoryArea interpolation="cardinal" padding="0" data={data} />
                                </VictoryStack>
                            </VictoryChart>
                        </div>

由于某种原因,useEffect 块中的“宽度”仅在窗口大小增加时更新。当它减小时,宽度保持不变。

难道我做错了什么?

非常感谢!

4

1 回答 1

0

After spending more time evaluating my setup, I've figured out that the problem was at the level, and not in the useEffect block. Adding a minWidth of 100% to the div made it update it's width when decreasing.

于 2020-12-11T07:04:44.583 回答