我有一个MapboxMap
React 组件,它初始化并渲染 Mapbox 地图(在map
const 下),并且需要在MapMarker
其中渲染组件。
这MapboxMap
看起来像:
import React from 'react'
import ReactDOM from 'react-dom'
import MapMarker from './MapMarker'
const MapboxMap = React.createClass({
componentDidMount(argument) {
mapboxgl.accessToken = 'access_token'
// This is what I want to access from inside of <MapMarker />
const map = new mapboxgl.Map({
container: ReactDOM.findDOMNode(this),
style: 'mapbox://styles/mapbox/streets-v8',
center: [-74.50, 40],
zoom: 9
})
},
render() {
const errors = this.props.errors
const photos = this.props.photos
return (
<div className='map'>
{errors.length > 0 && errors.map((error, index) => (
<pre key={index}>Error: {error}</pre>
))}
{errors.length === 0 && photos.map(photo => (
<MapMarker key={photo.id} photo={photo} />
))}
</div>
)
}
})
module.exports = MapboxMap
这是MapMarker
看起来的样子。
import React from 'react'
import ReactDOM from 'react-dom'
import MapboxMap from './MapboxMap'
const MapMarker = React.createClass({
render() {
const photo = this.props.photo
console.log(photo)
// I want to be able to access `map` inside of this component
return (
<div className='marker'></div>
)
}
})
module.exports = MapMarker
如何构建我的两个组件,以便我可以map
从两个组件访问,但专门在组件内部呈现地图MapboxMap
?