React中google-maps-react的Map组件无法调整尺寸如何解决
google-maps-react 地图组件无法调整实际尺寸解决方案
问题表现
直接为Map组件传入style属性设置宽高,仅会缩小组件内部嵌入的地图内容大小,无法改变组件本身的外层容器尺寸。即便传入style={{ width: '10%', height: '10%'}}做测试,组件本身仍会默认渲染为width: 100%、height: 100%的大小。
问题复现代码如下:
import React, { Component } from 'react'; import { Map, GoogleApiWrapper, Marker } from 'google-maps-react'; var config = require("../config/config").default(); export class GoogleMap2 extends Component { constructor(props) { super(props); this.state = { stores: [{lat: 47.49855629475769, lng: -122.14184416996333}, {latitude: 47.359423, longitude: -122.021071}, {latitude: 47.2052192687988, longitude: -121.988426208496}, {latitude: 47.6307081, longitude: -122.1434325}, {latitude: 47.3084488, longitude: -122.2140121}, {latitude: 47.5524695, longitude: -122.0425407}] } } displayMarkers = () => { return this.state.stores.map((store, index) => { return <Marker key={index} id={index} position={{ lat: store.latitude, lng: store.longitude }} onClick={() => console.log("You clicked me!")} /> }) } render() { return ( <Map google={this.props.google} zoom={8} style={{ width: '10%', height: '10%'}} initialCenter={{ lat: 47.444, lng: -122.176}} > {this.displayMarkers()} </Map> ); } } export default GoogleApiWrapper({ apiKey: config.apiKey, signature: config.signature })(GoogleMap2)
问题效果截图:
问题原因
google-maps-react的Map组件中,style属性仅作用于内部的地图画布层,组件外层的承载容器默认被强制设置为width: 100%、height: 100%,不会读取style属性里的宽高配置。
解决方法
- 方法1:外层套自定义尺寸的父容器(官方推荐方案)
利用Map组件默认撑满父容器的特性,在外层包裹一个自定义宽高的容器,同时给父容器设置position: relative避免地图定位偏移。
核心修改代码:render() { return ( {/* 自定义尺寸的外层容器 */} <div style={{ width: '400px', height: '300px', position: 'relative' }}> <Map google={this.props.google} zoom={8} initialCenter={{ lat: 47.444, lng: -122.176}} > {this.displayMarkers()} </Map> </div> ); } - 方法2:通过
containerStyle属性控制外层容器尺寸Map组件提供了专属的*containerStyle属性*用来控制外层承载容器的样式,style属性保留给内部地图画布使用,直接给该属性传宽高配置即可生效。
核心修改代码:<Map google={this.props.google} zoom={8} // 内部地图画布撑满外层容器 style={{ width: '100%', height: '100%'}} // 控制外层组件的实际尺寸 containerStyle={{ width: '300px', height: '250px', position: 'relative' }} initialCenter={{ lat: 47.444, lng: -122.176}} > {this.displayMarkers()} </Map>
注意:如果使用百分比设置宽高,必须保证父级元素有明确的可计算的宽高值,否则百分比尺寸会因找不到参照基准失效。
内容的提问来源于stack exchange,提问作者Harshit Jain
相关产品推荐
相关产品推荐

