我正在尝试使用 react 状态来制作动态多边形,但传单多边形不会被重新渲染。
目标是创建用户在 map 中单击创建的多边形。
class SimpleExample extends React.Component {
constructor() {
super();
this.state = {
positions: [[51.505, -0.09]]
};
}
addPosition = (e) => {
const {positions} = this.state
console.log('Adding positions', positions)
positions.push([e.latlng.lat, e.latlng.lng])
this.setState({positions})
}
render() {
console.log('Should render new positions', this.state.positions)
const staticPositions = [[51.505, -0.09], [51.4958128370432, -0.10728836059570314], [51.49602657961649, -0.09956359863281251]]
return (
<Map
center={[51.505, -0.09]}
onClick={this.addPosition}
zoom={13}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<Polygon positions={this.state.positions} color="blue" />
<Polygon positions={staticPositions} color="red" />
<Polyline positions={this.state.positions} />
</Map>
);
}
}
请检查这个 fiddle : https://jsfiddle.net/cesargdm/j2g4ktsg/1/
最佳答案
您可以将其复制到 jsfiddle 中,它应该可以工作。希望对您有所帮助。
我的初始状态为空数组,因此您的第一次单击决定您开始绘制 <Polygon>
的位置。 ,当然你可以使用初始坐标,这完全取决于你。
使用箭头函数(prevState) => {}
您可以根据您的“先前状态”正确更新状态,这里我们采用新坐标并使用 concat()
将其添加到我们的 positions
状态。
您可以找到有关更新状态的更多信息 here .
const React = window.React;
const { Map, TileLayer, Marker, Popup, Polygon } = window.ReactLeaflet;
class SimpleExample extends React.Component {
constructor() {
super();
this.state = {
positions: []
};
}
addPosition = (e) => {
const newPos = [e.latlng.lat, e.latlng.lng];
this.setState(prevState => (
{
positions: prevState.positions.concat([newPos])
}
));
}
render() {
return (
<Map
center={[51.505, -0.09]}
onClick={this.addPosition}
zoom={13}>
<TileLayer attribution='© <ahref="http://osm.org/copyright">
OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<Polygon positions={this.state.positions} color="blue" />
</Map>
);
}
}
window.ReactDOM.render(<SimpleExample />,
document.getElementById('container'));
关于javascript - React-Leaflet 多边形不会被重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889170/