我正在使用React Google Maps将 Google map 添加到我的页面,我正在此处设置 map :
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
export const MapWithMarkers = withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(props.lat), lng: parseFloat(props.long) }}
>
{props.markers.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
))
但是,我想注入(inject)一个商店并使用 this.props.store.lat
而不是 props.lat
,使用 @inject('store ')
,这需要将 MapWithMarkers 转换为类而不是 const。
我尝试过以下方法:
import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
@inject('store') @observer
export class MapWithMarkers extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
}
renderMarkers = (props) => {
<GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
>
{this.props.store.todos.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
}
render() {
const props = this.props;
return withScriptjs(withGoogleMap(this.renderMarkers()));
}
}
这不起作用,返回:
Uncaught (in promise) Error: MapWithMarkers.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
我做错了什么?
最佳答案
withScriptjs
和 withGoogleMap
是 HOC,您应该将 HOC 传递给组件。所以你的组件应该看起来像这样:
import React from "react";
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
@inject('store') @observer
export class Map extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
render() {
return <GoogleMap
defaultZoom={17}
center={{ lat: parseFloat(this.props.store.lat), lng: parseFloat(this.props.store.long) }}
>
{this.props.store.todos.map(marker => (
<Marker
key={marker.todoId}
position={{ lat: parseFloat(marker.lat), lng: parseFloat(marker.long) }}
/>
))}
</GoogleMap>
}
}
export const MapWithMarkers = withScriptjs(withGoogleMap(Map))
关于javascript - react : Convert HOC const to component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494656/