Как задать onclick кнопкам в балуне в react-yandex-map
Кажется, что вопрос уже избитый, но все же. Не отрабатывает oncliсk на кнопках. Если делаю не через ObjectManager, а через Clusterer, то onclick отрабатывает, но при переключении кластеров точки рисуются вечность, чего быть не должно. Буду признателен за помощь.
const MapWrapper = (props) => {
const dispatch = useDispatch();
window.balloonButtonClickHandler = (index) => {
props.setCurrentPoint(createCollection().features[index])
};
const Balloon = (el,index) => {
let balloon = ``;
const {subway, time, address, timeLabel, title} = el;
switch (props.currentServiceToGetOrder.id){
case "pn":
balloon = `
<ul>
<li>${title}</li>
<li><b>${timeLabel}</b></li>
<li>${address}</li>
<li>${time}</li>
</ul>
<input type="button" onclick={window.balloonButtonClickHandler(${index})} value="Забрать бесплатно"/>
`
return balloon;
case "pochta":
case "SdekAll":
case "pp":
balloon = `
<ul>
<li>${timeLabel}</li>
<li><b>${address}</b></li>
<li><b>${title}</b></li>
<li>${time}</li>
</ul>
<input type="button" onclick={window.balloonButtonClickHandler(${index})} value="Выбрать"/>
`
return balloon;
}
}
const createCollection = () => {
let points = {};
let servicesArr = props.deliveries.filter((service, idx) => {
if(service.type === "pickup") {
return service;
}
});
servicesArr.forEach((el) => {
points[`${el.id}`] = {
type:"FeatureCollection",
features: el.locations,
}
})
const result = {};
if (typeof points[`${props.currentServiceToGetOrder.id}`] !== "undefined") {
result.type = points[`${props.currentServiceToGetOrder.id}`].type;
const features = points[`${props.currentServiceToGetOrder.id}`].features.map((el) => {
let point = el;
point.geometry = {
type: "Point",
coordinates: [el.lat, el.lon],
}
point.properties = {}
point.properties.balloonContentBody = `${Balloon(el)}`;
return point
})
result.features = features;
}
return result
}
return (
createCollection().hasOwnProperty("features") ?
<Line >
<YMaps >
<Map onLoad={
()=>{dispatch(setLoader(false))}
}
defaultState={{
center: [props.currentCity.lat, props.currentCity.lon],
zoom: 9,
}}
modules={[
'templateLayoutFactory',
'geoObject.addon.balloon',
'clusterer.addon.balloon',
]}
style={{width:"100%", height:"300px"}}
>
<ObjectManager
options={{
clusterize: true,
gridSize: 32,
}}
objects={{
openBalloonOnClick: true,
preset: 'islands#greenDotIcon',
}}
clusters={{
preset: 'islands#redClusterIcons'
}}
features={createCollection().features}
modules={['objectManager.addon.objectsBalloon']}
>
</ObjectManager>
{/*<Clusterer*/}
{/* options={{*/}
{/* preset: "islands#invertedVioletClusterIcons",*/}
{/* }}>*/}
{/* {*/}
{/* createCollection().features.map((point, index) => {*/}
{/* return <Placemark*/}
{/* modules={[ //чтобы видеть хинты и балуны подключаем данные модули*/}
{/* 'objectManager.addon.objectsBalloon',*/}
{/* 'objectManager.addon.objectsHint',*/}
{/* ]}*/}
{/* key={index}*/}
{/* geometry={point.geometry.coordinates}*/}
{/* properties={{*/}
{/* balloonContentFooter:`*/}
{/* ${Balloon(point, index)}*/}
{/* `*/}
{/* }}*/}
{/* options={{*/}
{/* iconLayout: 'default#image',*/}
{/* }}*/}
{/* />*/}
{/* })*/}
{/* }*/}
{/*</Clusterer>*/}
</Map>
</YMaps>
</Line>
:
null
)
}
Ответы (2 шт):
Автор решения: George
→ Ссылка
Вы можете использовать фабрику шаблонов yandex.maps, чтобы создать собственный макет балуна и добавить в него свои события.
Надеюсь, это ответит на ваш вопрос.
Автор решения: ghetto-coder
→ Ссылка
оказалось, я забыл передать idx в Balloon(el, <тут должен был быть id элемента>). передал и все заработало.