在React中传递任意回调/参数

时间:2017-05-25 10:41:20

标签: javascript google-maps reactjs

我想将回调传递给地图组件,这需要能够提供我想要的任何参数。我试试

MapView.js:

import React, { Component } from 'react';
import { browserHistory } from 'react-router';


export default class MapView extends Component {

    constructor(props){
        super(props);
        this.renderMap = this.renderMap.bind(this);
        this.addMarkerToMap = this.addMarkerToMap.bind(this);
        this.clickMarker = this.clickMarker.bind(this);
    }

    componentDidMount() {
        this.renderMap();
    }

    renderMap() {
        let map_data = {
            zoom: this.props.zoom || 10,
            center: this.props.center || {lat: 30.3, lng: -97.75}  // default to Austin
        };

        let this_map = new google.maps.Map(this.refs.map, map_data);

        let markers_data = this.props.markers_data || [];
        markers_data.map(function(data) {
            this.addMarkerToMap(data, this_map);
        }.bind(this));
    }

    addMarkerToMap(data, the_map) {
        let marker = new google.maps.Marker({
            position: data.coordinates,
            map: the_map
        });
        if (data.callback) {
            let params = data.params || [];
            marker.addListener('click', data.callback.bind(this, ...params));
        }
        return marker
    }

    clickMarker(item_id, pathname) {
        // http://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router
        browserHistory.push(
            {
                pathname: pathname,
                query: { item_id: item_id } // https://stackoverflow.com/questions/36350644/how-can-i-pass-parameters-on-redirection-using-react-router
            }
        );
    }

    render() {
        return (
            <div>
                <h3>{this.props.title}</h3>
                <p>{this.props.description}</p>
                <div style={ {height: 500, width: 500 } } ref="map" />
            </div>
        )
  }
}

MapShowCustomers.js:

import React, {Component} from "react";
import { browserHistory } from 'react-router';

import MapView from './MapView';


export default class MapShowCustomers extends Component {

    constructor(props){
        super(props);
        this.clickMarker2 = this.clickMarker2.bind(this);
        this.exampleCallback = this.exampleCallback.bind(this);
    }

    clickMarker2(pathname, item_id) {
        alert(pathname);
        // http://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router
        browserHistory.push(
            {
                pathname: pathname,
                query: { item_id: item_id } // https://stackoverflow.com/questions/36350644/how-can-i-pass-parameters-on-redirection-using-react-router
            }
        );
    }

    exampleCallback(text) {
        console.log(text)
        if (text) {
            alert(text);
        } else {
            alert("it worked anyway");
        }
    }

    render() {
        let titleText = "This one to show customers for restaurant employees...more of a map example";
        let description = "Notice the usage of the 'center' prop...by overwriting the default center, this one shows up in Illinois (center={ {lat: 40.3, lng: -88.75} } )"
        let coordinates = {lat: 40.3, lng: -88.75};
        let markersData = [
            // {callback: this.clickMarker2, args: ['/profile-customer', 2], coordinates: {lat: 40.25, lng: -88.65}},
            // {callback: this.clickMarker2, args: ['/profile-customer', 7], coordinates: {lat: 40.35, lng: -88.85}},
            // {callback: this.clickMarker2, args: ['/profile-customer', 6], coordinates: {lat: 40.37, lng: -88.78}}
            {callback: this.exampleCallback, params: ["blah"], pathname: '/profile-customer', item_id: 1, coordinates: {lat: 40.25, lng: -88.65}},
            {callback: this.exampleCallback, params: ["blah"], pathname: '/profile-customer', item_id: 13, coordinates: {lat: 40.35, lng: -88.85}},
            {callback: this.exampleCallback, pathname: '/profile-customer', item_id: 37, coordinates: {lat: 40.37, lng: -88.78}}
        ];

        {/* look at the center prop for how to pass props...in GoogleMap component it defaults to Austin  */}
        return (
            <div>
                <MapView markers_data={markersData} center={coordinates} title={titleText} description={description}/>
            </div>
        );
    }
}

我尝试通过{callback: this.exampleCallback, pathname: '/profile-customer', item_id: 37, coordinates: {lat: 40.37, lng: -88.78}}通过没有params并看到exampleCallback警告“它仍然有效”通过做

if (data.callback) {
            let params = data.params || [];
            marker.addListener('click', data.callback.bind(this, ...params));
}

但现在我明白了:

enter image description here

它想要提醒[object Object]而不是“无论如何都有效”。可以在this repo看到此代码(尝试使用npm i; npm start)。

1 个答案:

答案 0 :(得分:1)

在addMarkerToMap中:

if (data.callback) {
  let params = data.params || [undefined];
  marker.addListener('click', data.callback.bind(this, ...params));
}

...params将数组解压缩到单独的参数中,例如将data.callback.bind(this, ...[1, 2, 3)解压缩到data.callback.bind(this, 1, 2, 3)。这是ES6中的新功能。默认为[undefined],您最终会解压缩到data.callback.bind(this, undefined),如果您的回调不需要参数,则会被忽略。