Access object from multiple React components

2019-06-10 03:35发布

I have a MapboxMap React component that initialises and renders a Mapbox map (under the map const), and needs to render MapMarker components inside of it.

This is what MapboxMap looks like:

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

This is what MapMarker looks like.

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

How can I structure my two components so that I can access map from both components, but specifically render the map inside of the MapboxMap component?

2条回答
smile是对你的礼貌
2楼-- · 2019-06-10 03:52

Create the map variable in some other Lifecycle method like componentWillMount() or componentWillReceiveProps() and assign the value of map to this.state via setState() method.

eg:

state = {map: {}}                           // defined a default state
componentWillReceiveProps(nextProps){
  map =  new mapboxgl.Map({ //your code });
  this.setState({ map: map});
}

Now, pass this.state.map as props to child MapMarker. Inside your render() method in <MapboxMap/>,

<MapMarker key={photo.id} photo={photo} map={this.state.map}/>

Now inside <MapMarker/> component the map from your parent <MapboxMap/> component will be accessible as this.props.map.

PS: Refer Component Specs and Lifecycle from React Docs for understanding where to use setState() method and where not.

查看更多
冷血范
3楼-- · 2019-06-10 04:04

Naisheel Verdhan's approach is good. I'd make one suggestion on top of that. Instead of setting the state in componentWillMount() or componentWillReceiveProps(), you can do it in getInitialState() (React.createClass syntax) or in the constructor() (ES2015, class extends React.Component syntax).

查看更多
登录 后发表回答