【问题标题】:Combining google-maps-react with react-router结合 google-maps-react 与 react-router
【发布时间】:2019-07-10 12:50:27
【问题描述】:

所以我正在渲染一组<Marker />google-maps-react 提供 问题是,当我添加来自react-router-dom<Link /> 时,google-maps-react 似乎并不喜欢它

这就是我把它放在一起的方式:

render() {
    return (
      <div>
        <Map
          google={this.props.google}
          zoom={14}
          styles={this.props.mapStyles}
          disableDefaultUI={true}
          onClick={this.saveCoords}
        >
          {this.state.data.map(m => {
            return (
              <Link to={`/c/contribution/${m.id}`}>
                <Marker position={{ lat: m.x, lng: m.y }} title={m.title} />
              </Link>
            )
          })}
        </Map>
      </div>
    )
  }

我尝试改用window.location,但这会重新加载页面,我不希望这样。

我在上面的代码中遇到了这个错误,这对我来说真的没有意义:

Warning: React does not recognize the `mapCenter` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `mapcenter` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

通过这个,我尝试实现一个可点击的&lt;Marker/&gt;,它将呈现另一个元素。可以通过转到代码示例中的Route 来访问这个特定的元素。

使用的路线:

<Route path='/c/contribution/:id' component={Contribution} />

【问题讨论】:

  • 您可以提供更多代码吗? (路由和使用mapCenter 道具的地方)
  • 这里的问题不在于路由,因为我在 render() 之外使用了相同的 &lt;Link /&gt; 并且它可以工作。但我添加了它们。对于mapCenter,我不在任何地方使用它,这很奇怪。

标签: javascript reactjs react-router react-router-dom google-maps-react


【解决方案1】:

不幸的是,由于地图子项的渲染方式,您不能像这样用google-maps-react 包裹标记。我没有深入研究,所以我不清楚为什么它会以它的方式工作。

对于google-maps-react,我认为要附加点击处理程序,但这使得使用react-router 有点复杂。

为了更简单的路径,您可以尝试google-map-react 包。它的工作方式略有不同,但可以轻松地在地图上渲染几乎任何东西。

【讨论】:

    【解决方案2】:

    您可以在重定向标记上使用onClick 事件。为您要重定向到的路径设置一个 state 属性,如果该属性不是空字符串,则不要重新处理您的普通组件,而是返回一个 &lt;Redirect/&gt; 元素。

     constructor(props){
        super(props)
        this.state = {
          ...
          redirectTo:"
        };
    }
    
        this.setRedirect = (path)=>{
          this.setState({
          redirectTo:path
         }
       }
    
    render(){
    if(this.state.redirectTo !== "")
        return <Redirect to={this.state.redirectTo}/>
    else
     return (
          <div>
            <Map
              google={this.props.google}
              zoom={14}
              styles={this.props.mapStyles}
              disableDefaultUI={true}
              onClick={this.saveCoords}
            >
              {this.state.data.map(m => {
                return (
                    <Marker onClick={()=>this.setRedirect(`/c/contribution/${m.id}`)} position={{ lat: m.x, lng: m.y }} title={m.title} />
                )
              })}
            </Map>
          </div>
        )
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 2019-10-19
      相关资源
      最近更新 更多