Reactjs 如何引用react传单组件的传单层?

Reactjs 如何引用react传单组件的传单层?,reactjs,leaflet,react-leaflet,Reactjs,Leaflet,React Leaflet,我用传单在地图上描绘了一条相当长的道路。用户可以从列表中进行选择,我希望所选路径具有不同的颜色。再次更改状态和渲染太慢,我正在寻找更快的解决方案 传单路径元素有setStyle方法,所以我的第一个想法是使用它,而不是再次渲染。但如何参考传单层 class MyPathComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { if (nextProps.selected){

我用传单在地图上描绘了一条相当长的道路。用户可以从列表中进行选择,我希望所选路径具有不同的颜色。再次更改状态和渲染太慢,我正在寻找更快的解决方案

传单路径元素有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} />
    );
  }
}
那么,在这段代码中,我应该写什么来代替传单的多段线呢?

react传单中的组件有一个名为传单元素的属性。我相信你可以这样做:

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} />
    );
  }
}
请告诉我是否有任何问题适合您。

react传单中的组件具有名为“传单元素”的属性。我相信你可以这样做:

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} />
    );
  }
}

让我知道这些是否适合您。

使用React callback ref并添加到上面@Eric的答案的完整示例:

export default class MyMap extends Component {

  leafletMap = null;

  componentDidMount() {
    console.debug(this.leafletMap);
  }

  setLeafletMapRef = map => (this.leafletMap = map && map.leafletElement);

  render() {
    return (
      <Map
        ref={this.setLeafletMapRef}
      >
        <TileLayer
          attribution="Powered by <a href=&quot;https://www.esri.com&quot;>Esri</a>"
          url="http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
        />
      </Map>
    );
  }
}

使用React回调ref并添加到上面@Eric的答案的完整示例:

export default class MyMap extends Component {

  leafletMap = null;

  componentDidMount() {
    console.debug(this.leafletMap);
  }

  setLeafletMapRef = map => (this.leafletMap = map && map.leafletElement);

  render() {
    return (
      <Map
        ref={this.setLeafletMapRef}
      >
        <TileLayer
          attribution="Powered by <a href=&quot;https://www.esri.com&quot;>Esri</a>"
          url="http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
        />
      </Map>
    );
  }
}