我使用react-leaflet在地图上可视化了很长的路径。用户可以从列表中选择,我希望所选路径具有不同的颜色。更改状态并再次渲染太慢,我正在寻找更快的解决方案。
传单路径元素具有setStyle()方法,所以我的第一个想法是使用它而不是再次呈现。但是如何引用传单层呢?
class MyPathComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.selected){
this.setState({selected: true});
LEAFLET_POLYLINE.setStyle({
color: 'red'
});
}
return false;
}
render() {
return(
<Polyline polylines={this.props.path} />
);
}
}
那么在这段代码中我应该写些什么而不是LEAFLET_POLYLINE?
中的组件react-leaflet
具有称为的属性leafletElement
。我相信你可以做这样的事情:
class MyPathComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.selected){
this.setState({selected: true});
this.refs.polyline.leafletElement.setStyle({
color: 'red'
});
}
return false;
}
render() {
return(
<Polyline ref="polyline" polylines={this.props.path} />
);
}
}
需要注意的两件事:
leafletElement
是这里的重要部分。除了上面的代码,最好将其扩展Polyline
为您的自定义组件(此处的文档有限):
import { Polyline } from 'react-leaflet';
class MyPathComponent extends Polyline {
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.selected){
this.setState({selected: true});
this.leafletElement.setStyle({
color: 'red'
});
}
return false;
}
}
让我知道这是否对您有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句