如何在React Leaflet中将数据绑定到标记单击?

时间:2019-11-01 19:10:53

标签: javascript reactjs react-leaflet

我正在尝试绑定数据,以便当我单击标记时可以检索一个值,特别是我正在使用的json中一个名为“ station_id”的字段的ID。目前,当我单击制造商时,我正在控制台记录event.target:

    markerClick = (e) =>{
            console.log(e.target);
        }

 let markers =null;
        if(this.props.showStations) {
        markers = (

            this.props.stations.data.stations.map((station) =>
                <Marker 
                    position={[station.lat, station.lon]}
                    onClick={this.markerClick.bind(this, station)}>
                </Marker>
                )

        )
        }

我相信解决此问题的方法是通过绑定markerClick函数,但是我不确定如何正确地做到这一点。下面是我的代码:

App.js

import React, { Component } from 'react';
import Leaf from './components/Leaf';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewport: {
        height: "100vh",
        width: "100vw",
        latitude: 40.7128,
        longitude: -74.0060,
        zoom: 10
      },
      latitude: 40.7128,
      longitude: -74.0060,
      zoom: 10,
      stations: [],
      showStations: false,
      selectedStation: null,
      userLocation: {}
    };
  }

  componentDidMount() {
    const request = async()=> {
      await fetch('https://gbfs.citibikenyc.com/gbfs/en/station_information.json')
      .then(res => res.json())
      .then(res=>
        this.setState({stations: res, showStations: true}))
    }
    request();
  }

  checkData=()=>{
    console.log(this.state.stations)
    this.state.stations.data.stations.map(e=>{
      console.log(e)
    })
  }

  render() {

    return (
      <div>
          <button onClick={this.checkData}>click me</button>   
          <Leaf 
            viewport={this.state.viewport}
            stations={this.state.stations}
            showStations={this.state.showStations}/>
      </div>
    );
  }
}

export default App;

Leaf.js

import React, {Component} from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
//import './leaf.css'
//import InfoBox from './InfoBox';
import { Button } from 'react-bootstrap';
//import Search from './Search';
//import Match from './Match';
//import Modal from './Modal';
//import L from 'leaflet';
//import Routing from "./RoutingMachine";
//import { Row, Col, Grid, Container } from 'react-bootstrap';
//import ErrorBoundary from '../ErrorBoundary/ErrorBoundary'



class Leaf extends Component {


    checkData=()=>{
        this.props.stations.data.stations.map(e=>{
          console.log(e)
        })
      }

    markerClick = (e) =>{
        console.log(e.target);
    }

    render() {

        let markers =null;
        if(this.props.showStations) {
        markers = (

            this.props.stations.data.stations.map((station) =>
                <Marker 
                    position={[station.lat, station.lon]}
                    onClick={this.markerClick.bind(station)}>
                </Marker>
                )

        )
        }


        const position = [this.props.viewport.latitude, this.props.viewport.longitude]
        //const position = [40.7484, -73.9857]
        return (
            <div>
                <button onClick={this.checkData}>check props</button>
                <Map center={position} zoom={14}>
                    <TileLayer
                        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                      {markers}
                    <Marker position={position}>
                        <Popup>
                            A pretty CSS3 popup. <br /> Easily customizable.
                        </Popup>
                    </Marker>
                </Map>  
            </div>
        );
    }
}

export default Leaf;

2 个答案:

答案 0 :(得分:0)

我不认为您想要bindbind旨在用于授予对this的功能访问权限。正常变量应通过以下方法之一使用。

您可以将函数内联到此:

onClick={() => this.markerClick(station)}

或更改函数的签名并将其用于此:

markerClick = (station) => (e) =>{
  console.log(station);
}

....

onClick={this.markerClick(station)}

答案 1 :(得分:0)

使用Marker组件内的eventHandlers函数:

<Marker
  position={[50.5, 30.5]}
  eventHandlers={{
    click: (e) => {
      console.log('marker clicked', e)
    },
  }}
/>