我无法使用onMouseOver / onMouseOut事件显示/隐藏多边形。
到目前为止,我已经尝试通过this
直接操作选项,并使用通过道具传递的带有三元运算符的父项状态作为选项值。
const Map = compose(
withProps({
googleMapURL:
'https://maps.googleapis.com/maps/api/js?key=${APIKEY}&callback=initMap',
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: '100%' }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => {
return (
<GoogleMap
center={{ lat: 40.726, lng: -74.006 }}
defaultOptions={{
mapTypeId: 'roadmap',
zoom: 16,
minZoom: 15.5,
maxZoom: 18,
streetViewControl: false,
scaleControl: false,
mapTypeControl: false,
clickableIcons: false,
panControl: false,
zoomControl: true,
rotateControl: false,
scrollWheel: false,
gestureHandling: 'greedy'
}}
>
<Polygon
path={[
{ lat: 40.7290705, lng: -74.0105223 },
{ lat: 40.727603, lng: -74.0106457 },
{ lat: 40.7262451, lng: -74.0108174 },
{ lat: 40.7258874, lng: -74.0108495 },
{ lat: 40.72481, lng: -74.0092724 },
{ lat: 40.7241352, lng: -74.0083496 },
{ lat: 40.7234522, lng: -74.0073894 },
{ lat: 40.7221187, lng: -74.0054582 },
{ lat: 40.7222569, lng: -74.0054582 },
{ lat: 40.7255256, lng: -74.0041064 },
{ lat: 40.727729, lng: -74.0032052 },
{ lat: 40.7283306, lng: -74.0032159 },
{ lat: 40.7285908, lng: -74.0057479 },
{ lat: 40.7288347, lng: -74.0082156 },
{ lat: 40.7290705, lng: -74.0105223 }
]}
options={{
strokeColor: '#369BF7',
strokeOpacity: props.neighborhood.westVillage ? 1 : 0,
fillOpacity: props.neighborhood.westVillage ? 1 : 0,
strokeWeight: 1,
fillColor: '#369BF7'
}}
onMouseOver={() => {
console.log('westVillage');
props.toggleNeighborhoodVisibility('westVillage');
}}
onMouseOut={() => {
console.log('off');
props.toggleNeighborhoodVisibility('westVillage');
}}
/>
</GoogleMap>
);
});
class MapContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
neighborhood: {
soho: false,
tribeca: false,
hudsonSquare: false,
westVillage: false
}
};
}
toggleNeighborhoodVisibility = section => {
const { neighborhood } = this.state;
neighborhood[section] = !neighborhood[section];
this.setState({
neighborhood
});
};
render() {
const { neighborhood } = this.state;
return <Map neighborhood={neighborhood} toggleNeighborhoodVisibility={this.toggleNeighborhoodVisibility} />;
}
}
答案 0 :(得分:1)
由于在示例中使用了recompose
,因此您可以考虑通过withHandlers()
HoC将其他参数传递给toggleNeighborhoodVisibility
:
withHandlers({
handleMouseEvent: props => event => {
const polygon = props.polygonRef.current.state[POLYGON]; //polygon instance
props.toggleNeighborhoodVisibility("westVillage", polygon);
}
})
其中
<Polygon
ref={props.polygonRef}
//...
onMouseOver={props.handleMouseEvent}
onMouseOut={props.handleMouseEvent}
/>
说明:
polygonRef
ref用于访问Polygon组件