gribnoysup / react-yandex-maps

Yandex Maps API bindings for React
MIT License
327 stars 116 forks source link

Изменение SearchControl при выборе точки на карте #249

Closed madear closed 3 years ago

madear commented 4 years ago

Здравствуйте, можно ли изменять значение в searchcontrol при выборе точки на карте кликом?

mmarkelov commented 4 years ago

@madear почему нет?

import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import {
  YMaps,
  Map,
  SearchControl,
  Placemark
} from "react-yandex-maps";

import "./styles.css";

const mapState = { center: [55.750625, 37.626], zoom: 7 };

function App() {
  // храним текущий текст
  const [text, setText] = useState(null);
  // ref searchcontrol
  const searchRef = useRef(null);

  useEffect(() => {
    if (text && searchRef.current) {
      // Меняем текст searchcontrol при изменении text
      searchRef.current.search(text);
    }
  }, [text]);

  return (
    <div className="App">
      <YMaps>
        <Map>
          <SearchControl
            instanceRef={ref => {
              if (ref) searchRef.current = ref;
            }}
          />
          <Placemark
            geometry={[55.684758, 37.738521]}
            properties={{
              balloonContentBody: "Test 1"
            }}
            // инициализируем изменение текста при клике на метку
            onClick={() => setText("Test 1")}
          />
          <Placemark
            geometry={[55.254758, 37.538521]}
            properties={{
              balloonContentBody: "Test 2"
            }}
            onClick={() => setText("Test 2")}
          />
        </Map>
      </YMaps>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);