【问题标题】:Update tileLayer url in react-leaflet更新 react-leaflet 中的 tileLayer url
【发布时间】:2021-10-06 15:54:36
【问题描述】:

所以我运行这段代码来渲染传单,尝试在 colorMode 更改时替换 url 是这里的挑战。

useEffect 被触发,可以显示正确的变量,但我无法以任何方式更新该 TileLayer。

export const Map = () => {
    const { colorMode } = useColorMode();

    let state = { center: { lat: 51.505, lng: -0.09 }, zoom: 13 };

    const colorModeUrl = ['https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png']
    useEffect(() => {
      console.log(colorMode);
    }, [colorMode]);

    return (
        <MapContainer
            center={state.center}
            zoom={state.zoom}
            style={{ height: '100%' }}>
            <TileLayer url={colorMode === 'light' ? colorModeUrl[0] : colorModeUrl[1]} />
        </MapContainer>
    )
}

【问题讨论】:

  • 你试过了吗:{ colorMode === 'light' ? &lt;TileLayer url={colorModeUrl[0] /&gt; : &lt;TileLayer url={colorModeUrl[1] /&gt;?如果我正确阅读源代码,看起来TileLayer 只会更新zIndexopacity 道具,并且需要完全重新渲染以获取新的平铺网址github.com/PaulLeCam/react-leaflet/blob/…
  • 似乎只需在此处更新网址即可:codesandbox.io/s/react-leaflet-forked-1534x
  • 试过 @teddybeard 不起作用,即使组件使用正确的 url 重新渲染,它也不会在视觉上更新。对于代码框的想法,它与 chakra 提供的 colorMode 钩子不兼容,并且他们的 github 问题的解决方法看起来很脏

标签: javascript reactjs leaflet react-leaflet chakra-ui


【解决方案1】:

查看TileLayer documentationurl 属性是不可变的。初始渲染后,如果 prop 发生更改,组件将不会更新:

但是,您可以将ref 添加到图层并以这种方式更新网址

export const Map = () => {
  const ref = useRef(null);
  const state = { center: { lat: 51.505, lng: -0.09 }, zoom: 13 };
  const { colorMode } = useColorMode();

  const light = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
  const dark =
 "https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png";

  };

  useEffect(() => {
    if (ref.current) {
      ref.current.setUrl(colorMode === "light" ? light : dark);
    }
  }, [colorMode]);

  return (
    <div>
      <MapContainer
        center={state.center}
        zoom={state.zoom}
        style={{ height: "100%" }}
      >
        <TileLayer ref={ref} url={colorMode === "light" ? light : dark} />
      </MapContainer>
    </div>
  );
};

https://codesandbox.io/s/react-leaflet-forked-1534x?file=/src/index.js:0-1158

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2021-02-20
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多