我正在尝试使用nivo
制作响应式折线图。
我已经通过此MWE重新创建了尝试:
nivo
[如果我使浏览器更宽-折线图会像您期望的那样响应,将填充空白。
我所遇到的问题是,如果我使浏览器变窄,则该图的大小不会像它使它变宽时那样调整以填充浏览器宽度的100%。对于新的浏览器宽度,它仍然太宽。有趣的是,刷新图总是占据浏览器的100%。
当使浏览器变宽和变窄时,如何使图形占据浏览器的100%?
我已经通过在SO上回答以下问题来解决了这一问题:import React, { useState, useEffect } from "react";
import { ResponsiveLine } from "@nivo/line";
import styled from "styled-components";
const HoursGraphWrapper = styled.div`
display: grid;
grid-template-rows: 300px;
grid-template-columns: 1fr;
grid-gap: 10px;
`;
const useWindowWidth = () => {
let width, setWidth;
if (typeof window !== "undefined") {
[width, setWidth] = useState(window.innerWidth);
} else {
[width, setWidth] = useState(1001);
}
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
});
return width;
};
const TestGraph = () => {
const width = useWindowWidth();
return (
<HoursGraphWrapper>
<ResponsiveLine
data={[
{
id: "A",
data: [
{ x: "2019-01-11", y: 11 },
{ x: "2019-01-12", y: 20 },
{ x: "2019-01-13", y: 24 },
{ x: "2019-01-14", y: 25 },
{ x: "2019-01-15", y: 15 },
{ x: "2019-01-16", y: 50 },
{ x: "2019-01-17", y: 30 },
{ x: "2019-01-18", y: 31 }
]
},
{
id: "B",
data: [
{ x: "2019-01-11", y: 30 },
{ x: "2019-01-12", y: 24 },
{ x: "2019-01-13", y: 22 },
{ x: "2019-01-14", y: 15 },
{ x: "2019-01-15", y: 35 },
{ x: "2019-01-16", y: 45 },
{ x: "2019-01-17", y: 20 },
{ x: "2019-01-18", y: 11 }
]
}
]}
colors={{ scheme: "set1" }}
xScale={{
type: "time",
format: "%Y-%m-%d",
precision: "day"
}}
xFormat="time:%Y-%m-%d"
yScale={{
type: "linear",
stacked: false
}}
axisLeft={{
format: value => `${value}hr`,
legend: "Total Hours",
legendOffset: -50,
legendPosition: "middle"
}}
axisBottom={{
format: "%b %d",
legend: "Date",
legendOffset: 36,
legendPosition: "middle",
tickValues: width < 1000 ? 5 : undefined
}}
curve="monotoneX"
enablePoints={width > 1000}
pointBorderWidth={1}
useMesh={true}
enableSlices={false}
margin={{ top: 10, right: 20, bottom: 60, left: 80 }}
animate={true}
/>
</HoursGraphWrapper>
);
};
export default TestGraph;
解决方案是使用以下样式在Flex items not shrinking when window gets smaller图形周围添加div包装器:
ResponsiveLine