Javascript Can';是否在react挂钩中调整d3 v6的大小?
我正在尝试从状态调整svg的宽度和高度:Javascript Can';是否在react挂钩中调整d3 v6的大小?,javascript,reactjs,d3.js,Javascript,Reactjs,D3.js,我正在尝试从状态调整svg的宽度和高度: const [svgWidth, setSvgWidth] = useState(350); const [svgHeight, setSvgHeight] = useState(250); useEffect(() => { const svg = d3 .select("#epi-chart") .attr("width", svgWidth)
const [svgWidth, setSvgWidth] = useState(350);
const [svgHeight, setSvgHeight] = useState(250);
useEffect(() => {
const svg = d3
.select("#epi-chart")
.attr("width", svgWidth)
.attr("height", svgHeight);
const margin = { top: 0, right: 10, bottom: 10, left: 10 },
width = svgWidth - margin.left - margin.right,
height = svgHeight - margin.top - margin.bottom;
const x = d3.scaleLinear().rangeRound([0, width]);
const y = d3.scaleBand().rangeRound([0, height]).padding(0.4);
const g = svg
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain([0, d3.max(mockData, (d) => Number(d.col1)) as number]);
y.domain(
mockData.map(function (d) {
return d.letter;
})
);
g.selectAll(".bar")
.data(mockData)
.enter()
.append("rect")
.attr("fill", "rgba(105, 129, 148, 0.4)")
.attr("class", "bar1")
.attr("x", 0)
.attr("y", (d) => y(d.letter) as number)
.attr("width", (d) => x(Number(d.col1)))
.attr("height", y.bandwidth())
.attr("rx", 21)
.attr("ry", 21);
g.selectAll(".bar2")
.data(mockData)
.enter()
.append("rect")
.attr("fill", "url(#bg-gradient)")
.attr("filter", "drop-shadow(0 0 4px #418bfa)")
.attr("class", "bar2")
.attr("x", 0)
.attr("y", (d) => y(d.letter) as number)
.attr("width", (d) => x(Number(d.col2)))
.attr("height", y.bandwidth())
.attr("rx", 21)
.attr("ry", 21);
}, [svgWidth, svgHeight]);
我正在使用材质ui,我更改宽度和高度如下:
const isScreenDownMd = useMediaQuery(theme.breakpoints.down("md"));
useEffect(() => {
if (isScreenDownMd) {
setSvgWidth(300);
setSvgHeight(200);
}
}, [isScreenDownMd]);
但我得到的结果是这样的,这是混乱的:
为什么会这样?我建议将宽度和高度放在一个对象中:
const [svgSize, setSvgSize] = useState({width: 350, height: 250});
,然后更改isScreenDownMd
:
useEffect(() => {
if (isScreenDownMd) {
setSvgSize({width: 300, height: 200});
}
}, [isScreenDownMd]);
。。。以及:
useEffect(() => {
const svg = d3
.select("#epi-chart")
.attr("width", svgSize.width)
.attr("height", svgSize.height);
...
}, [svgSize]);