簡體   English   中英

如何將數據綁定到 React Leaflet 中的標記單擊?

[英]How to bind data to a Marker click in 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 function,但我不確定如何正確執行。 下面是我的代碼:

應用程序.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;

在 Marker 組件中使用 eventHandlers function:

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

我不認為你想要bind bind是為了讓 function 訪問this 正常變量應通過以下方法之一使用。

您可以將您的 function 內聯到此:

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

或更改您的 function 的簽名並將其咖喱:

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

....

onClick={this.markerClick(station)}

暫無
暫無

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

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