React-Leaflet-自定义图钉,OnClick链接到另一页

时间:2019-04-16 19:41:11

标签: reactjs react-router leaflet react-leaflet

我与自定义图钉(通过divIcon)集成了反应叶

const divIcon = L.divIcon({
      className: '',
      html: ReactDOMServer.renderToString(
          <CustomPin pinColour={pinColour} pinCode={pinCode} pinID={id} history={history} />
      ),
      iconSize: [24, 40],
      iconAnchor: [12, 40],
      popupAnchor: [0, -40]
});

如果我想在用户单击自定义图标时进行重定向,该怎么做?

显然不可能在ReactDOMServer.renderToString中包含一个标签。

是否可以解决此问题?

1 个答案:

答案 0 :(得分:2)

在index.js上定义两条路由:

const App = () => {
  return (
    <Router>
      <Route exact path="/" component={MapLeaflet} />
      <Route path="/another-page" component={AnotherPage} />
    </Router>
  );
};

MapLeaflet将是包含地图和AnotherPage的组件,例如单击标记后将重定向到的另一个组件。

然后在您的MapLeaflet组件中

<Marker
    position={position}
    icon={customMarker}
    onClick={() => this.props.history.push("/another-page")}>

使用onClick事件从Marker导航到另一页路线

我可以选择包括从AnotherPage comp导航回'/'路线的可能性。

我还使用了L.icon而不是L.divIcon。希望对你没事。

Demo