在映射数组中反应OnScroll事件侦听器

时间:2017-09-23 02:53:55

标签: javascript reactjs dom refs

我正在尝试对其进行设置,以便在滚动从数组映射的图像时,使用该图像的坐标更新状态,从而更新Google地图。

<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
    })
}

并在滚动特定图像时更新地图?

1 个答案:

答案 0 :(得分:0)

如果这对其他人有帮助,我使用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>
    )
}

}