首页 > 解决方案 > 从父组件的状态传递子组件中的道具

问题描述

我无法在 Google 地图组件上使用从父组件到子组件的状态。这听起来可能是一个非常基本的问题,但是我试图了解其中一个道具有效与其他无效之间的区别。

所以我有一个谷歌地图组件(从'google-map-react'导入GoogleMapReact)

static defaultProps = {
    center: { lat: 62.10281, lng: -84.14565 },
    zoom: 11
  };

  constructor(props) {
   console.log(props);       
    super(props);
  }

  render() {

      return (
        <div className='google-map' style={{ height: '100%', width: '100%' }}>
          <GoogleMapReact
            bootstrapURLKeys={{ key: 'somekey' }}
            center={this.props.center}
            defaultZoom={ this.props.zoom }>
            <AnyReactComponent
              lat={ this.props.lat }
              lng={ this.props.lng }
              text={ 'Wheres Waldo?' }
            />
          </GoogleMapReact>
        </div>
      )
  }

然后从父组件

<MapComponent lat={this.state.latitude} lng={this.state.longitude}
                    center={{lat: this.state.latitude, lng: this.state.longitude}}

我已经在构造函数中检查了 lat、lng 和 center 的值,并且按预期得到它们仍然 map 不起作用

但是,如果我硬编码中心的值,让 lat 和 lng 从状态中获取值,那么它确实有效。

现在这有效,有人可以解释这个概念和区别以及如何克服它吗?感谢您的帮助。

<MapComponent lat={this.state.latitude} lng={this.state.longitude}
                    center={{lat: 62.10281, lng: -84.14565}}

标签: reactjs

解决方案


推荐阅读