React中map函数内渲染Marker组件并传参失败求助
解决React中map循环渲染Marker组件的问题
我帮你梳理下代码里的几个问题,咱们一步步修复:
问题1:无法访问objMarkers变量
你在构造函数里声明了objMarkers,但没有把它挂载到组件实例的this上,同时style变量也没挂载到this,导致render方法里根本拿不到这两个变量。需要调整构造函数的写法:
constructor(props) { super(props); // 将style和objMarkers挂载到组件实例上 this.style = { width: '100%', height: '100%' }; this.objMarkers = [ { title: "The marker`s title will appear as a tooltip.", name: "Soma", position: [35.85472104, 14.48779873] // 把坐标字符串改成数字类型 }, { title: "The marker`s title will appear as a tooltip.", name: "Soma", position: [35.9220325, 14.37038234] // 统一转成数字格式 } ]; }
问题2:JSX中循环的写法错误
在Map组件内部,不能直接写return this.objMarkers.map(...),需要用**花括号{}**包裹JS表达式,而且不需要额外的return,直接返回map的结果即可。另外,循环渲染的每个组件必须加上唯一的key属性,帮助React高效识别列表项。
问题3:Position的类型错误
Google Maps的Marker组件需要数值类型的经纬度,你原来的坐标是字符串格式,会导致组件无法正确解析位置,所以要去掉引号转成数字。
修正后的完整代码
import React, { Component } from 'react'; import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react'; export class MapContainer extends Component { constructor(props) { super(props); this.style = { width: '100%', height: '100%' }; this.objMarkers = [ { title: "The marker`s title will appear as a tooltip.", name: "Soma", position: [35.85472104, 14.48779873] }, { title: "The marker`s title will appear as a tooltip.", name: "Soma", position: [35.9220325, 14.37038234] } ]; } render() { return ( <Map google={this.props.google} style={this.style} initialCenter={{lat: 35.85472104, lng: 14.48779873}} zoom={11} > {/* 用花括号包裹循环逻辑,添加唯一key属性 */} {this.objMarkers.map((marker, index) => ( <Marker key={index} // 如果marker有唯一ID字段,优先用marker.id替代index title={marker.title} name={marker.name} position={{ lat: marker.position[0], lng: marker.position[1] }} // 转成Marker识别的lat/lng对象格式 /> ))} </Map> ); } } const LoadingContainer = (props) => ( <div>Fancy loading container!</div> ) export default GoogleApiWrapper({ apiKey: ("AIzaSyBHq-A0EL3usDeqH5q8B635Rafxcguc0a8"), LoadingContainer: LoadingContainer })(MapContainer)
额外说明
- 关于
key属性:如果你的marker数据里有唯一标识(比如id),优先使用key={marker.id},比index更稳定,能避免列表更新时出现不必要的重渲染。 Marker的position属性既支持数组[lat, lng]也支持对象{lat: xxx, lng: xxx},上面的代码用对象格式更直观清晰。
内容的提问来源于stack exchange,提问作者Reynier Téllez
相关产品推荐
相关产品推荐

