簡體   English   中英

帶有Google Maps的ReactJS-隨時顯示一個信息窗口

[英]ReactJS with Google Maps - displaying one info window at any time

我正在使用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>
        )
}

由於每個標記都有其自己的狀態,因此您必須找到一種方法來連接每個標記組件的每個狀態對象。 之所以需要每個標記的狀態,是因為當單擊一個標記時,它必須通知所有其他標記有一個標記被單擊,因此如果它們的窗口打開,則必須立即將其關閉。 在這種情況下,我建議您使用Redux解決此問題(因為您說過您還不熟悉React,所以我不確定您是否已經熟悉Redux,所以如果您願意,請告訴我評論,我將嘗試使用Redux幫助提供解決方案)。 我相信,即使沒有Redux的幫助,您仍然可以解決問題,但是將來可能會變得非常復雜且難以控制。

此外,我認為代碼中有幾件事需要首先解決。 將狀態內部的isOpen設置為布爾值而不是字符串會更好。 因此,這是您應該對代碼進行的更改:

  1. 在構造函數中,初始化isOpen

    this.state = {isOpen:false}

  2. 在handleToggleOpen函數內部,不需要傳遞任何參數,因此您可以刪除e

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

這基本上就是切換功能,因此您也可以刪除handleToggleClose函數(以及handleToggleOpen處理打開和關閉的功能),然后將其替換為render函數中的handleToggleOpen

  1. 現在你只需要改變

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

簡單地

this.state.isOpen &&

那么它應該可以按預期的方式工作,而無需每次都比較每個標記的ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM