簡體   English   中英

在映射數組中反應OnScroll事件偵聽器

[英]React OnScroll event listener in mapped array

我正在嘗試進行設置,以便在滾動從數組映射的圖像時,使用該圖像的坐標來更新狀態,從而更新Google Map。

<CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto">
  <div className="image-holder">
    {displayImages.map((displayImage, i) => {
      return (
        <div
          className="responsive"
          key={i}
          ref="img"
          onScroll={this.handleScroll(this.state.images[i].location)}>
          <div className="img">
            <a
              target="_blank"
              href={`http://res.cloudinary.com/gdbdtb/image/upload/${displayImage}.jpg`}>
              <Image publicId={displayImage} responsive style={{width: '100%'}}>
                <Transformation crop="scale" width="auto" responsive_placeholder="blank" />
              </Image>
            </a>
          </div>
        </div>
      );
    })}
  </div>
</CloudinaryContext>

通過閱讀其他一些問題,我設置了以下生命周期方法:

componentDidMount() {
    const imgDiv = ReactDOM.findDOMNode(this.refs.img)
    imgDiv.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
    const imgDiv = ReactDOM.findDOMNode(this.refs.img)
    imgDiv.removeEventListener('scroll', this.handleScroll);
}

但是, ReactDOM.findDOMNode(this.refs.img)始終返回undefined

我可以打電話叫什么方式

handleScroll(location) {
    this.setState({
        center: location
    })
}

並在滾動特定圖像時更新地圖嗎?

如果這對其他人有幫助,我可以使用React-Waypoints插件解決此問題:

import React, { Component } from 'react'
import { Header, ImageBoard, AccountNav, AlbumBoard } from '../modules'
import {Router, Route, Redirect, Link, withRouter } from 'react-router-dom'
import { APIManager } from '../utils'
import ReactDOM from 'react-dom'
import {Image, CloudinaryContext, Transformation} from 'cloudinary-react';
import { compose, withProps, lifecycle } from "recompose";
const Waypoint = require('react-waypoint');
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker
} from "react-google-maps";


export default class Album extends Component {
constructor(){
    super()
    this.toLatLng.bind(this),
    this.handleScroll = this.handleScroll.bind(this),
    this.state = {
        images: [],
        center: { lat: 25.03, lng: 121.6 }
    }
}

toLatLng (coord) {
    const latLng = {lat: coord[1], lng: coord[0]}
    return latLng
}

componentWillMount(){
    APIManager.get(`/api/album/${this.props.match.params.id}`, null, (err, response) => {
        if(err){
            let msg = err.message || err
            console.log(msg)
            return
        }

        let images = response.result[0].albums.images

        this.setState({
            images: images,
            center: this.toLatLng(images[0].location)
        })
    })
}


handleScroll(location){
    this.setState({
        center: this.toLatLng(location)
    })
}


render(){

    const Map = compose(
          withProps({
            googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyAsv9Hz2-CqDOgrb4FBSkfC-4aTiJL13cI",
            loadingElement: <div style={{ height: `100%` }} />,
            containerElement: <div style={{ height: `calc(100vh - 100px)`, position: 'fixed', left: '70vw' }} />,
            mapElement: <div style={{ width: `30vw`, height: `100%`}} />,
            center: this.state.center,
          }),
          withScriptjs,
          withGoogleMap,
        )(props =>
          <GoogleMap
            defaultZoom={14}
            defaultCenter={props.center}
          >
          {this.state.images.map((image, i) => {
              return (
                  <Marker key={i}
                      position={this.toLatLng(image.location)}
                  />
              )
          })}
          </GoogleMap>
        );


    const toPublicId = (image) => {
        return image.slice(62, image.length)
    }


    return(
        <div>
            <Header />
            <Map />
            <div className="albumImageBoard">
                <CloudinaryContext  cloudName="djswgrool" fetchFormat="auto" >
                  <div className="image-holder" ref="imgDiv">

                      {this.state.images.map((image, i) => {
                          return (
                              <div className="responsive" key={i}>
                                  <div className="img">
                                      <a target="_blank" href={`http://res.cloudinary.com/djswgrool/image/upload/${toPublicId(image.url)}.jpg`}>
                                          <Image publicId={toPublicId(image.url)} responsive style={{width: '100%'}} >
                                              <Transformation
                                                  crop="scale"
                                                  width="auto"
                                                  responsive_placeholder="blank"
                                              />
                                          </Image>
                                      </a>
                                  </div>
                                  <Waypoint
                                    onEnter={ () => this.handleScroll(image.location)}/>
                              </div>

                          )
                      })
                  }
                  </div>
                </CloudinaryContext>
            </div>
        </div>
    )
}

}

暫無
暫無

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

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