[英]React - How can I render a component within a class by using OnClick?
I am new to React and still learning how things work.我是 React 的新手,仍在学习事情是如何工作的。 I would like to programatically generate some google-maps-react.Polyline once the Marker is clicked.单击标记后,我想以编程方式生成一些 google-maps-react.Polyline 。
I can create the Polylines by rendering directly in the class return.我可以通过直接在 class 返回中渲染来创建折线。 However, I have no idea on how to dynamically generate it on click.但是,我不知道如何在点击时动态生成它。 I tried the code below but it didn't work.我尝试了下面的代码,但没有成功。
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
})
render(){
return(
<>
{pathCoordinates.coordinates.map(item =>
<Polyline
path={item}
geodesic={true}
options={{
strokeColor: "#ff2527",
strokeOpacity: 0.3,
strokeWeight: 1,
icons: [
{
icon: lineSymbol,
offset: "0",
repeat: "2px"
}
]
}}
/>)}
</>
)
}
;
Here you can find the whole class code:在这里您可以找到整个 class 代码:
export class WhereWeFly extends Component {
state = {
showingInfoWindow: false, // Hides or shows the InfoWindow
activeMarker: {}, // Shows the active marker upon click
selectedPlace: {} // Shows the InfoWindow to the selected place upon a marker
};
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
onClose = props => {
if (this.state.showingInfoWindow) {
this.setState({
showingInfoWindow: false,
activeMarker: null
});
}
};
render() {
return (
<>
<div className='wherewefly' id='wherewefly'>
<div className='wwf-title' id='wwf-title'>
<h1>
<i class='fas fa-map-marker'></i>
<span>Where do we fly to?</span>
</h1>
</div>
<Map
google={this.props.google}
zoom={zoom}
style={mapStyles}
initialCenter={initCenter}>
{markers.marker.map(item =>
<Marker
onClick={this.onMarkerClick}
name={item.location}
position={ {
lat: item.lat,
lng: item.lng
}}
/>)}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div className='wwf-marker'>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
{pathCoordinates.coordinates.map(item =>
<Polyline
path={item}
geodesic={true}
options={{
strokeColor: "#ff2527",
strokeOpacity: 0.3,
strokeWeight: 1,
icons: [
{
icon: lineSymbol,
offset: "0",
repeat: "2px"
}
]
}}
/>)}
</Map>
</div>
</>
);
}
}
How can I programatically generate the polylines?如何以编程方式生成折线?
I created a new state called clicked and made a conditional render as below:我创建了一个名为 clicked 的新 state 并进行了条件渲染,如下所示:
clicked: true
{this.state.clicked && pathCoordinates.coordinates.map(item =>
<Polyline
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.