如何参考反应小叶组件的小叶层?

elc*_*iga 1 leaflet reactjs react-leaflet

我使用react-leaflet在地图上可视化很长的路径.用户可以从列表中进行选择,我希望所选路径具有不同的颜色.更改状态和再次渲染太慢,我正在寻找更快的解决方案.

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} />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

那么我应该在这段代码中编写什么而不是LEAFLET_POLYLINE

Eri*_*arr 5

组件中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} />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

有两点需要注意:

  1. 我没有测试过这段代码,所以可能需要一些小的调整.
  2. 在React中使用字符串作为"ref"被认为是遗留的,所以你可能想要做一些稍微不同的事情(见这里).这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;
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有任何问题,请告诉我.