React Leaflet:动态设置 GeoJSON 的样式

React Leaflet: setting a GeoJSON's style dynamically

我正在尝试根据其 ID 是否与选择器匹配来动态更改 GeoJSON 组件的样式。

插件的作者参考了Leaflet documentation,其中说样式应该作为函数传递。我正在做,但没有骰子。

我的组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Marker, Popup, GeoJSON } from 'react-leaflet';
import { centroid } from '@turf/turf';

const position = geoJSON => {
    return centroid(geoJSON).geometry.coordinates.reverse();
};

export class PlotMarker extends Component {
    render() {
        const {
            id,
            name,
            geoJSON,
            zoomLevel,
            selectedPlot,
            plotBeingEdited
        } = this.props;
        const markerPosition = position(geoJSON);
        let style = () => {
            color: 'blue';
        };
        if (selectedPlot === id) {
            style = () => {
                color: 'red';
            };
        }
        if (zoomLevel > 14) {
            return (
                <GeoJSON
                    id={id}
                    data={geoJSON}
                    style={style}
                    onClick={() => {
                        this.props.selectPlot(id);
                    }}
                />
            );
        }
        return (
            <Marker
                id={id}
                className="marker"
                position={markerPosition}
                onClick={() => {
                    this.props.selectPlot(id);
                }}>
                <Popup>
                    <span>{name}</span>
                </Popup>
            </Marker>
        );
    }
}

function mapStateToProps(state) {
    return {
        selectedPlot: state.plots.selectedPlot,
        plotBeingEdited: state.plots.plotBeingEdited,
        zoomLevel: state.plots.zoomLevel
    };
}

export default connect(mapStateToProps, actions)(PlotMarker);

好的,知道了。这与我定义样式函数的方式有关。这不起作用:

let style = () => {
    color: 'blue';
};
if (selectedPlot === id) {
    style = () => {
        color: 'red';
    };
}
if (zoomLevel > 14) {
    return (
        <GeoJSON
            id={id}
            data={geoJSON}
            style={style}
            onClick={() => {
                this.props.selectPlot(id);
            }}
        />
    );
}

这个有效:

let style = () => {
    return {
        color: 'blue'
    };
};
if (selectedPlot === id) {
    style = () => {
        return {
            color: 'red'
        };
    };
}
if (zoomLevel > 14) {
    return (
        <GeoJSON
            id={id}
            data={geoJSON}
            style={style}
            onClick={() => {
                this.props.selectPlot(id);
            }}
        />
    );
}