javascript - 无法在 Recompse 中使用 Props

标签 javascript reactjs google-maps

我是 React 的新手,我设法将谷歌地图添加到我的项目中。

google 包使用 recompose 的问题,但是当我在其中调用 props 时无法获取我的数据 props 为空:

我的 map :

import { compose, withProps } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"

const MyMapComponent = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withScriptjs,
  withGoogleMap
)((props) =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: this.props.lat, lng:  this.props.lat }}
  >
    {props.isMarkerShown && <Marker position={{ lat: this.props.lat, lng:  this.props.lat }} />}
  </GoogleMap>
));

MyMapComponent 调用:

<MyMapComponent lat={this.state.lat} long={this.state.long}/>

最佳答案

Props 通过 props 参数传递给 GoogleMap 组件,而不是绑定(bind)到 this 上下文,这里是修改后的版本

<GoogleMap
    defaultZoom={4}
    defaultCenter={{ lat: props.lat, lng:  props.long }}  >
    {props.isMarkerShown && <Marker position={{ lat: props.lat, lng:  props.long }} />}
</GoogleMap>

一些其他的变化

  • 设置经度的例子有一些错别字
  • 通常不需要指定 Google Maps API 版本,因此 参数 v 可以省略

  • 对于提供的示例,附加库的加载不是 必需的,所以 libraries 也可以省略

Demo

关于javascript - 无法在 Recompse 中使用 Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51498727/

相关文章:

react : ShouldComponentUpdate for states

Javascript - 从 rawOffset Google 时区 API 计算时间

javascript - 单击“追加”按钮,然后再次单击“返回”。?

javascript - 在页面上选择和突出显示 html 的最佳方式是什么?

javascript - 如何将url参数与返回的数据关联起来?

java - 如何让 map 标记始终保持在屏幕中央?安卓

javascript - 在 apache cordova 中获取 "google not defined"

javascript - 将函数传递给innerHTML方法

javascript - ng-repeat 中的输入附加函数

javascript - 在最后一张幻灯片上停止 jQuery 按钮事件