gpt4 book ai didi

reactjs - 当中心状态改变时,React 传单中心属性不会改变

转载 作者:行者123 更新时间:2023-12-03 15:27:04 24 4
gpt4 key购买 nike

App.js

import { useState } from 'react';

const App = () => {
// This state is used to the center attribute of MapContainer component
const [mapCenter, setMapCenter] = useState([34.80746, -40.4796]);
// This state is used to the zoom attribute of MapContainer component
const [mapZoom, setMapZoom] = useState(3);

const onClickHandler = () => {
setMapCenter([20, 100]);
setMapZoom(5);
};

return (
<>
<button onClick={onClickHandler}>Change map's center location</button>
<Map center={mapCenter} zoom={mapZoom} />
</>
);
};
Map.js
import React from 'react';
import './Map.css';
import { MapContainer, TileLayer } from 'react-leaflet';

function Map({ center, zoom }) {
return (
<div className="map">
<MapContainer center={center} zoom={zoom}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a
href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
</MapContainer>
</div>
);
}

export default Map;
Map.css
.map {
height: 500px;
background-color: white;
padding: 1rem;
border-radius: 20px;
margin-top: 16px;
box-shadow: 0 0 8px -4px rgba(0, 0, 0, 0.5);
}

.map .leaflet-container {
height: 100%;
}
当我单击按钮时,mapCenter 状态明显更改为 [20, 100] 并且 mapZoom 也更改为 5。但在 Map Component Map 中没有显示新的中心。但我不知道为什么。我已经检查了状态的变化。
map 从不响应。有人知道吗???请回答一个弄清楚的方法。

最佳答案

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.The Leaflet Map instance created by the MapContainer element can be accessed by child components using one of the provided hooks or the MapConsumer component.
https://react-leaflet.js.org/docs/api-map


ChangeView.js
function ChangeView({ center, zoom }) {
const map = useMap();
map.setView(center, zoom);
return null;
}
Map.js
function Map({ center, zoom }) {
return (
<div className="map">
<MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
<ChangeView center={center} zoom={zoom} />
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
</MapContainer>
</div>
);
}
react-leaflet 文档使用 setCenter在它的 useMapEvent example ,但是这个函数没有定义。但是在传单文档中 Methods for modifying map state有一个功能 setView(center, zoom, options?) .

关于reactjs - 当中心状态改变时,React 传单中心属性不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64665827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com