Onclick 在地图容器上不起作用,有人可以帮忙吗?
<块引用>函数handleMapClick:
function handleMapClick(event: LeafletMouseEvent) {
const { lat, lng } = event.latlng;
setPosition({
latitude: lat,
longitude: lng,
});
}
<块引用>
带有 onClick 的 MapContainer:
<MapContainer
center={[-29.9518154,-51.1689972]}
style={{ width: '100%', height: 280 }}
zoom={15}
onClick={handleMapClick}
>
import React, { useState } from "react";
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
import Map from 'react-leaflet';
import { LeafletMouseEvent } from 'leaflet';
import { FiPlus } from "react-icons/fi";
import Sidebar from "../components/Sidebar";
import mapIcon from "../utils/mapIcon";
import '../styles/pages/create-ong.css';
export default function CreateOng() {
const [position, setPosition] = useState({ latitude: 0, longitude: 0 })
function handleMapClick(event: LeafletMouseEvent) {
const { lat, lng } = event.latlng;
setPosition({
latitude: lat,
longitude: lng,
});
}
return (
<div id="page-create-ong">
<Sidebar />
<main>
<form className="create-ong-form">
<fieldset>
<legend>Dados</legend>
<MapContainer
center={[-29.9518154,-51.1689972]}
style={{ width: '100%', height: 280 }}
zoom={15}
onClick={handleMapClick}
>
<TileLayer
url={`https://api.mapbox.com/styles/v1/mapbox/light-v10/tiles/256/{z}/{x}/{y}@2x?access_token=${process.env.REACT_APP_MAPBOX_TOKEN}`}
/>
{ position.latitude !== 0
? <Marker interactive={false} icon={mapIcon} position={[position.latitude, position.longitude]} />
: null
}
</MapContainer>
<div className="input-block">
<label htmlFor="name">Nome</label>
<input id="name" />
</div>
<div className="input-block">
<label htmlFor="about">Sobre <span>Máximo de 300 caracteres</span></label>
<textarea id="name" maxLength={300} />
</div>
<div className="input-block">
<label htmlFor="images">Fotos</label>
<div className="uploaded-image">
</div>
<button className="new-image">
<FiPlus size={24} color="#15b6d6" />
</button>
</div>
</fieldset>
<fieldset>
<legend>Visitação</legend>
<div className="input-block">
<label htmlFor="instructions">Instruções</label>
<textarea id="instructions" />
</div>
<div className="input-block">
<label htmlFor="opening_hours">Nome</label>
<input id="opening_hours" />
</div>
<div className="input-block">
<label htmlFor="open_on_weekends">Atende fim de semana</label>
<div className="button-select">
<button type="button" className="active">Sim</button>
<button type="button">Não</button>
</div>
</div>
</fieldset>
<button className="confirm-button" type="submit">
Confirmar
</button>
</form>
</main>
</div>
);
}
答案 0 :(得分:0)
您可以使用 OnClick
钩子将 <MapContainer />
处理程序添加到 useMapEvent
:
function handleMapClick(event: LeafletMouseEvent) {
const { lat, lng } = event.latlng;
setPosition({
latitude: lat,
longitude: lng,
});
}
...
useMapEvent('click', handleMapClick)
完整示例:https://react-leaflet.js.org/docs/example-react-control/
答案 1 :(得分:0)
如果您熟悉 React 中的组件,请使用类组件。这最适合改变网页上不同元素的状态