带有Google Maps的ReactJS-随时显示一个信息窗口

时间:2018-07-09 16:30:05

标签: javascript reactjs react-google-maps

我正在使用react-google-maps,并且能够显示标记和InfoWindow-正常工作,但是我只想显示当前的活动标记窗口。

我正在使用isOpen状态存储当前标记,并显示它是否与当前键匹配,但是仍然可以单击并切换所有标记信息窗口。我怀疑我犯了一个非常简单的错误,但是我对ReactJS还是很陌生。另外,请注意,我发现了非常相似的问题,但是没有一个问题可以帮助我解决此问题。

这是我的代码。

    constructor(props){
    super(props);

    this.state = {
        isOpen: '',
    }

}

handleToggleOpen = (e) => {

   this.setState({
       isOpen: e
   });

   console.log(e);
   console.log('current state is... ');
   console.log(this.state.isOpen);
}

handleToggleClose = () => {
    this.setState({
        isOpen: null
    });
}

render() {

    // console.log(this.props.marker.id)

    return (

            <div>
        <Marker
            key={this.props.marker.id}
            position={{ lat: parseFloat(this.props.marker.acf.locations.lat), lng: parseFloat(this.props.marker.acf.locations.lng)}}
              icon={{
               url: this.props.icon,
               optimized: false,
               scaledSize: new google.maps.Size(25, 37),
             }}
             onClick={() =>  this.handleToggleOpen(this.props.marker.id)}
             audioPlay={this.props.audioPlay} >

                {
                        this.state.isOpen === this.props.marker.id && (
                     <InfoWindow onCloseClick={this.handleToggleClose}>
                        <div>
                         <h3 className="infowindow__title">{this.props.marker.title.rendered} {this.props.marker.acf.title_sub} </h3>
                         <span onClick={() =>this.refs.componentToDisplay.showPopup()} className="infowindow__link underline">Learn more</span>
                        </div>
                     </InfoWindow>)
                    }

            <PlacePopup ref="componentToDisplay" title={this.props.marker.title.rendered} intro={this.props.marker.acf.text} id={this.props.marker.id} subtitle={this.props.marker.acf.title_sub} audio={this.props.marker.acf.file} audioPlay={this.props.audioPlay}  >
                        </PlacePopup>
        </Marker> 
    </div>
        )
}

1 个答案:

答案 0 :(得分:0)

由于每个标记都有其自己的状态,因此必须找到一种方法来连接每个标记组件的每个状态对象。之所以需要每个标记的状态,是因为当单击一个标记时,它必须通知所有其他标记有一个标记被单击,因此如果它们的窗口打开,则必须立即将其关闭。在这种情况下,我建议您使用Redux解决此问题(因为您说过您还不熟悉React,所以我不确定您是否已经熟悉Redux,所以如果您愿意,请告诉我评论,我将尝试使用Redux帮助提供解决方案)。我相信,即使没有Redux的帮助,您仍然可以解决问题,但是将来可能会变得非常复杂且难以控制。

此外,您认为代码中有几件事需要首先解决。将状态内的isOpen设置为布尔值而不是字符串会更好。因此,这是您应该对代码进行的更改:

  1. 在构造函数中,初始化isOpen

    this.state = {     isOpen:否 }

  2. 在handleToggleOpen函数内部,不需要传递任何参数,因此您可以删除e

    handleToggleOpen =()=> {     this.setState({         isOpen:!this.state.isOpen     }); }

这基本上就是切换功能,因此您也可以删除handleToggleClose函数(因为handleToggleOpen处理打开和关闭),然后在渲染函数中将其替换为handleToggleOpen

  1. 现在您只需要更改

this.state.isOpen === this.props.marker.id &&

简单地

this.state.isOpen &&

然后它应该按预期的方式工作,而不必每次都比较每个标记的ID。

相关问题