Cannot read properties of undefined (reading 'storage') в react-yandex-map 2.1
я хочу создать кнопку, которая будет показывается в зависимости от пользователя, который открыл ее. Шаблон для балунов я пишу в html, поэтому я не могу указать параметр disable=false
. Он его просто не будет видеть. document.getElementById("buttun2").disabled = false;
тоже не помогает. Я попытался решить проблему с помощью ymaps.templateLayoutFactory.createClass
но когда я пытаюсь прикрепит его к ключу с помощью ymaps.layout.storage.add
он выкидывает ошибку
Cannot read properties of undefined (reading 'storage')
TypeError: Cannot read properties of undefined (reading 'storage')
Вот полный код, где я это использую. Пусть вас не смущает отсутствующие части кода, т.к. оттуда были вырезаны ненужные куски. Прошу любой подсказки а то я уже отчаялся. Спасибо!
import React, { useState,useEffect } from 'react';
import { YMaps, Map, Clusterer , Button,Placemark } from '@pbe/react-yandex-maps';
import "../css/ballon.css"
import Header from "./Header";
import {Modal} from "react-bootstrap";
const mapState = {
center: [55.7924886417031, 49.12233672582469],
zoom: 9
};
const YMap = () => {
const placemarkRef = React.useRef(null);
const mapRef = React.useRef(null);
const [address, SetAddress] = React.useState("");
const [count, setValue] = useState(0);
const [canAddPlacemark, checkAddPlacemark] = useState(false);
const [oldRegionName, addOldRegionName] = useState();
const [oldRegion, addOldRegion] = useState();
const [ymaps, setYmaps] = useState(React.useRef(null));
const [openedDescription, openDescription] = useState(null);
const [clusterBalloon, setClusterBalloon] = useState(null);
const closeDescription = () => {
setClusterBalloon(null);
openDescription(null);
};
const createPlacemark = (coords) => {
return new ymaps.current.Placemark(
coords,
{
iconCaption: "loading.."
},
{
preset: "islands#violetDotIconWithCaption",
draggable: true
}
);
};
let regionName = "";
const getAddress = async (coords) => {
placemarkRef.current.properties.set("iconCaption", "loading..");
await ymaps.current.geocode(coords).then((res) => {
const firstGeoObject = res.geoObjects.get(0);
const newAddress = [
firstGeoObject.getLocalities().length
? firstGeoObject.getLocalities()
: firstGeoObject.getAdministrativeAreas(),
firstGeoObject.getThoroughfare() || firstGeoObject.getPremise()
]
.filter(Boolean)
.join(", ");
SetAddress(newAddress);
placemarkRef.current.properties.set({
iconCaption: newAddress,
balloonContent: ' <div> <input type="button" onClick={() => { openDescription(index);}} value="Подробнее"/> </div>'
});
regionName =firstGeoObject.getAdministrativeAreas()[0];
})
};
const markers = [ {
"coord": "55.79424260833246,49.68814042729016",
"id": 1,
"author": "Abdul",
},
{
"coord": "55.62832515119459, 49.11135820072768",
"id": 2,
"author": "Abdul",
},
{
"coord": "55.910118447321, 48.70761064213393",
"id": 3,
"author": "Abdul",
}
]
const addMarkers = () =>{
markers.forEach(marker => {
var balloonContentLayout = ymaps.templateLayoutFactory.createClass(
'<div class="cd-quick-view">' +
'<div class="cd-slider-wrapper">' +
'<ul class="cd-slider">' +
'</ul>' +
'<li><img src="https://w7.pngwing.com/pngs/616/389/png-transparent-isolated-animal-leopard-safari-wildlife-africa.png" width="200" height="100"></li>' +
'<ul class="cd-slider-navigation">' +
'</ul>' +
'</div>' +
'<div class="cd-item-info">' +
'<h2>Produt Title</h2>' +
`<p>Автор метки: ${marker.author}</p>` +
`<p>Инфа о воздухе: пока нет</p>` +
'<ul class="cd-item-action">' +
'<li>' +
'<button id="buttun1" class="add-to-cart1" disabled>Add to cart</button>' +
'<button id="buttun2" class="add-to-cart2">Add to cart</button>' +
'<button id="buttun3" class="add-to-cart3">Add to cart</button>' +
'</li>' +
'</ul>' +
'</div>' +
'</div>'
);
ymaps.layout.storage.add('tinko#officeslayout', balloonContentLayout);
var placemark = new ymaps.Placemark(marker.coord.split(','), {
balloonHeader: 'Заголовок балуна',
// balloonContent:balloonContentLayout,
balloonContentBodyLayout:'tinko#officeslayout',
balloonFooter: 'Футер балуна'
},{
balloonShadow: true,
// balloonLayout: balloonContentBody,
// Запретим замену обычного балуна на балун-панель.
// Если не указывать эту опцию, на картах маленького размера откроется балун-панель.
balloonPanelMaxMapArea: 1,
hideIconOnBalloonOpen: false
});
// Добавим метку на карту.
mapRef.current.geoObjects.add(placemark);
// document.getElementById("buttun2").disabled = false;
// document.getElementById("buttun2").setAttribute('disabled','true')
});
}
const onMapClick = (e) => {
var objectId = e.get('id')
console.log(objectId)
if (canAddPlacemark){
let objectManager = new ymaps.current.ObjectManager();
objectManager.options.set('geoObjectInteractivityModel', 'default#transparent');
const coords = e.get("coords");
if (placemarkRef.current) {
placemarkRef.current.geometry.setCoordinates(coords);
} else {
placemarkRef.current = createPlacemark(coords);
mapRef.current.geoObjects.add(placemarkRef.current);
placemarkRef.current.events.add("dragend", function () {
getAddress(placemarkRef.current.geometry.getCoordinates());
});
}
getAddress(coords);
}
};
function sayHello() {
setValue(count+1);
if(count % 2 != 0){
checkAddPlacemark(canAddPlacemark => !canAddPlacemark)
}
else{
checkAddPlacemark(canAddPlacemark => !canAddPlacemark)
}
}
return (
<div>
<Header/>
<YMaps query={{
// load: "package.full" ,
apikey: "106e4ebf-abbc-41b9-9230-adfbc64f15d9" }}>
<Map defaultState={{
center: [55.751574, 37.573856],
zoom: 9
}}
modules={["Clusterer","Polygon","GeoObject","geoQuery","control.ZoomControl", "control.FullscreenControl","Placemark", "geocode",
"geoObject.addon.balloon","borders", "ObjectManager",'geoObject.addon.balloon','clusterer.addon.balloon',
'templateLayoutFactory']}
style={{
flex: 2,
height: "calc(100vh - 57px)"
}}
onClick={onMapClick}
instanceRef={mapRef}
onLoad={ymaps => setYmaps(ymaps)}
state={mapState}
>
<Button onClick={sayHello} data={{ content: 'Button' }} options={{ float: 'right' }} />
<Button onClick={addMarkers} data={{ content: 'Вывод маркеров' }} options={{ float: 'right' }} />
</Map>
<Modal show={show2} onHide={handleClose2}>
<Modal.Header closeButton className="backcolorBlack">
<Modal.Title>Edit Message</Modal.Title>
</Modal.Header>
<Modal.Body className="backcolorBlack">
<form>
<div className="form-group">
<label>[Full Name]:</label>
<input type="text" className="form-control" placeholder="User Full Name..." />
</div>
<div className="form-group">
<label> Email:</label>
<input type="email" className="form-control" placeholder="Email..."
/>
</div>
</form>
</Modal.Body>
<Modal.Footer className="backcolorBlack">
<Button variant="danger" onClick={handleClose2}>
Cancel
</Button>
<Button variant="primary" onClick={() => {
console.log("friend To Edit");
handleClose2();
}}>
Update
</Button>
</Modal.Footer>
</Modal>
</YMaps>
</div>
)
}
export default YMap;
Источник: Stack Overflow на русском