从另一个文件中的类调用函数

时间:2019-11-12 22:10:15

标签: javascript reactjs

我有一个Google Map,我正在尝试使用Google Autocomplete搜索来更新地图中心。我将搜索栏与最新地图功能放在单独的JSX文件中。如何从我的搜索栏文件中调用此函数?以下是我尝试的操作,通过此操作我在上面的注释行中收到错误TypeError: __WEBPACK_IMPORTED_MODULE_1__map__.a.recenterMap is not a function

Here is my working example,这是我的代码(根据AlainIb的响应进行了更新):

map.js

export class MapContainer extends React.Component {
  ...
  recenterMap(lat, lng) {
    const map = this.map;

    const google = this.props.google;
    const maps = google.maps;

    if (map) {
      let center = new maps.LatLng(lat, lng);
      map.panTo(center);
    }
  }
  ...
}
export default MapContainer;

这是我的 searchbar.jsx 文件:

import MapContainer from './map';
/* global google */

class SearchBar extends Component {
  ...
  handlePlaceChanged(){
    const place = this.autocomplete.getPlace();
    this.setState({ lat: place.geometry.location.lat() });
    this.setState({ lng: place.geometry.location.lng() });
    /* WHAT I TRIED */
    MapContainer.recenterMap(this.state.lat, this.state.lng);
  }
  ...
}

export default SearchBar;

2 个答案:

答案 0 :(得分:1)

您不能那样做。 extends React.Component的类只能作为组件调用(在带有<MapContainer />的jsx中或作为TabNavigator或StackNavigator等的一部分进行路由)

1)您可以执行以下操作:在SearchBar组件中添加一个回调函数,当调用handlePlaceChanged()以将其设置为lat和lng时,该回调函数将被调用,该回调函数将作为道具传递给地图组件

  • 在map.js中

    export class MapContainer extends React.Component {
      ...
      recenterMap() {             
         const {lat,lng} = this.props;
         ...
      }
     shouldComponentUpdate(nextProps) {
             const diffLat= this.props.lat!== nextProps.lat;
             const diffLng = this.props.done !== nextProps.lng
             return diffLat|| diffLng ;
     }
      ...
    }
    
  • 在SearchBar.js中

    export class SearchBar extends React.Component {
       ...
        handlePlaceChanged {
          ...
           this.props.updateParentState(lat, lng);
        }
    
      ...
    }
    
  • 在父组件中

    <SearchBar updateParentState={(lat,lng)=>{this.setState({ lat,lng }) }} />
    <MapContainer  lat={this.state.lat} lng={this.state.lng} />   
    

2)如果maps.js没有呈现功能,请将其更改为功能

export function recenterMap(lat, lng,map,google) {
    // pure logic
} 

答案 1 :(得分:0)

如果您要共享功能。假设,centralerMap不需要共享状态。您可以将centralerMap函数从组件中带入其他实用程序类。将所需的数据作为参数传递给此函数。

class ComponentUtility {
static recenterMap(lat, lng, propGoogle) {
    const map = this.map;
    const maps = propGoogle.maps;

    if (map) {
        let center = new maps.LatLng(lat, lng);
        map.panTo(center);
    }
}

}

您可以像下面这样调用此静态方法:

ComponentUtility.recenterMap(lat, lng, propGoogle);

您只需要传递正确的值即可。