繁体   English   中英

设置 react-mapbox-gl 的宽度

[英]Setting the width for the react-mapbox-gl

我试图使地图响应我的网站,所以我添加了 if 语句,但它不起作用,宽度仅在我手动编辑时更改。 有人可以帮忙解决这个问题,但我不明白为什么它不起作用

let phone = "320";
let tablet = "900";
let bigScreen = "2600";
let bigLaptop = "1400";
let laptop = "1000";
function useWindowSize() {
  const [width, setWidth] = useState(calculateWidth());
  useEffect(() => {
    function updateSize() {
      console.log("hey");
      setWidth(calculateWidth());
    }

    window.addEventListener("resize", updateSize);

    return () => {
      console.log();
      window.removeEventListener("resize", updateSize);
    };
  }, []);

  function calculateWidth() {
    if (window.innerWidth < bigScreen && window.innerWidth > bigLaptop) {
      return "70vw";
    } else if (window.innerWidth < bigLaptop && window.innerWidth > laptop) {
      return "67vw";
    } else if (window.innerWidth < laptop && window.innerWidth > phone) {
      return "60vw";
    } else {
      return "100vw";
    }
  }
  return width;
}

//For map API location Bali
export function Map() {
  const mediaWidth = useWindowSize();
  console.log();
  const [viewport, setViewport] = useState({
    latitude: -8.340539,
    longitude: 115.091949,
    width: mediaWidth,
    height: "100vh",
    zoom: 10,
  });

您应该像这样使用 useEffect 跟踪mediawidth变化值。

useEffect(() => {
  setViewport(state => ({
    ...state,
    width: mediaWidth
  }));
}, [mediaWidth]);

但也许您可以使用 Flexbox、CSS 网格布局或媒体查询来轻松实现您想要做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM