我从 App 组件状态设置面板组件的属性。当我单击按钮时,我想增加(示例)地图坐标。没关系,但我必须在 Panel 的 componentDidMount() 中声明 openlayers 变量,但 componentDidMount 一旦运行,坐标不会改变地图我该怎么办?请帮忙 ... 。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Panel from './Map'
class App extends Component {
constructor() {
super();
this.state = {
coordinates: [46.41, 40.82]
}
}
render() {
return (
<div >
<Panel coordinates={this.state.coordinates} />
<div><button onClick={() => {
this.setState({
coordinates: [this.state.coordinates[0] + 1, this.state.coordinates[1]]
})
}}>Go</button></div>
</div>
);
}
}
export default App;
面板组件
import React from 'react'
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import proj from 'ol/proj/';
import { fromLonLat } from 'ol/proj';
export default class Panel extends React.Component {
constructor() {
super();
this.state = {
crd: [46, 40]
}
}
GetCoordinates() {
return this.state.crd
}
componentWillReceiveProps(prp) {
this.setState({ crd: prp.coordinates })
}
componentDidMount() {
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: fromLonLat(this.GetCoordinates()) // i need set here,
zoom: 7
})
});
}
render() {
return <div id="map" style={{ width: '700px', height: '500px' }}></div>
}
}