[英]React-Learflet - Change circle opacity when clicked
当我单击它以充当活动 state 时,我正在尝试更改我的圆圈不透明度
我宣布了我的 state
const [active, setActive] = useState(false)
我的 function
const sidebarTrigger = () => {
setActive(true)
}
这就是我试图改变它的方式,在我的MapContainer 中
fillOpacity= {active ? '0.9' : '0.7'}
地图容器
<MapContainer whenCreated={setMap} center={[selectedRegion['lat'],selectedRegion['long']]} zoom={selectedRegion['zoom']} scrollWheelZoom={true}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{props.regionC.map((item,i) => {
<Circle
eventHandlers={{ click: sidebarTrigger.bind(this, item.city,item.lat,item.long) }}
center={item.city === 'Johannesburg' || item.city === 'Johhensburg' ? [-26.195246,28.034088] : [item.lat ,item.long]}
color= '#EE7E18'
fillColor="#EE7E18"
fillOpacity= {active ? '0.9' : '0.7'}
weight="0"
radius={radius}
/>
)
}
})}
</MapContainer>
React Leaflet docs state 子组件的 props 是不可变的:
默认情况下,这些道具应被视为不可变的,只有在此页面中明确记录为可变的道具才会在更改时影响 Leaflet 元素。
所以这就解释了为什么当你改变active
的值时<Circle>
的不透明度不会更新。
如果您使用 ref,这将允许您对 Circle 执行操作。 在下面的代码中,我们获得了<Circle>
的引用,并且click
事件处理程序调用updateActiveState()
来更新活动 state 的值:
const circleRef = useRef();
const updateActiveState = () => {
setActive((prevState) => !prevState);
};
...
<Circle
eventHandlers={{
click: () => {
updateActiveState();
},
}}
...
fillOpacity={active ? '0.9' : '0.5'}
...
ref={(ref) => {
circleRef.current = ref;
}}
/>
然后,您可以定义一个调用 Leaflet 的setStyle方法的效果,以根据active
的值更新 Circle 的fillOpacity
。 只要active
的值发生变化,就会执行此操作:
useEffect(() => {
if (circleRef.current) {
circleRef.current.setStyle({ fillOpacity: active ? '0.9' : '0.5' });
}
}, [active]);
有关工作演示,请参阅此 StackBlitz 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.