簡體   English   中英

無法在反應鈎子中調整 d3 v6 的大小?

[英]Can't resize d3 v6 in react hooks?

我正在嘗試使用 state 的寬度和高度調整我的 svg 的大小:

  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]);

但我得到的結果是這樣的:

在此處輸入圖像描述

為什么會這樣?

我建議將寬度高度放在一個 object 中:

  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]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM