1

我的应用程序使用 areact-leaflet来生成带有标记和弹出窗口的地图。我需要通过<Link/>来自react-router.

/* app.js */
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './components/App';
import Map from './components/Map';

const Root = () =>
  <Router history={browserHistory}>
    <Route path='/' component={App}>
      <Route path='map' component={Map} />
    </Route>
  <Router>

render(<Root />, document.getElementById('root'));


/* components/Map/index.js */
import React from 'react';
import { Router, Route, browserHistory } from 'react-router';
import App from './components/App';
import Map from './components/Map';

const Map = () =>
  <Map>
    <Marker position={[10, 10]}>
      <Popup>
        <div>
          <Link to="/">Main page</Link>
        </div>
      </Popup>
    </Marker>
  <Map>

export default Map;

但是通过链接我得到一个错误:

在路由器上下文之外呈现的 <Link> 无法导航。

这是因为打开的 Popup 的内容从路由器上下文中移除并放在下面。

我想,我可以放入router.push()Popup。但也许可以使用 a<Link/>吗?

谢谢!

4

1 回答 1

2

所以,我创建了ContextProvider组件创建器:

import React, { PureComponent, PropTypes } from 'react';

export default function createContextProvider(context) {
  class ContextProvider extends PureComponent {
    static propTypes = {
      children: PropTypes.node,
    };
    static childContextTypes = {};

    getChildContext() {
      return context;
    }

    render() {
      return this.props.children;
    }
  }

  Object.keys(context).forEach((key) => {
    ContextProvider.childContextTypes[key] = PropTypes.any.isRequired;
  });

  return ContextProvider;
}

并将其用于创建地图标记:

import React, { PureComponent, PropTypes } from 'react';
import { Marker, Popup } from 'react-leaflet';
import createContextProvider from '../ContextProvider';

export default class SomeComponent extends PureComponent {
  static contextTypes = {
    router: PropTypes.object,
    // Place here any other parameters from context
  };

  render() {
    const { position, children, ...props } = this.props;
    const ContextProvider = createContextProvider(this.context);

    return (
      <Marker {...props} position={position}>
        <Popup>
          <ContextProvider>
            <div>
              {children}
            </div>
          </ContextProvider>
        </Popup>
      </Marker>
    );
  }
}
于 2017-03-01T09:07:29.003 回答