首页 > 解决方案 > 选择一个选项后,如何让我的 Popup 自动出现在 reactJS 中?Leaflet-js

问题描述

我正在使用 Leaflet JS

export const showDataOnMap = (data, casesType ='cases', selectedCountry) => 
data.map(country => (
    <Circle
        center={[country.countryInfo.lat, country.countryInfo.long]}
        fillOpacity={0.4}
        pathOptions={country.countryInfo.iso2 === selectedCountry
                        ? casesTypeColors[casesType].highlight /* if selectedCountry then highlight circle! */
                        : casesTypeColors[casesType].option
        }   
        
    radius = {
        Math.sqrt(country[casesType]) * casesTypeColors[casesType].multiplier / 2
    }
    >
    
    <Popup popupopen={country.countryInfo.iso2 === selectedCountry ? Popup.openPopup()}>
        <div className="info-container">
            <div
                className='info-flag'
                style={{backgroundImage: `url(${country.countryInfo.flag})`}}
            />
            <div className='info-name'>{country.country}</div>
            <div className='info-cases'>Cases: {numeral(country.cases).format("0,0")}</div>
            <div className='info-recovered'>Recovered: {numeral(country.recovered).format("0,0")}</div>
            <div className='info-deaths'>Deaths: {numeral(country.deaths).format("0,0")}</div>
        </div>
    </Popup>
</Circle>

当我从下拉菜单中选择一个选项时,也就是“country.countryInfo.iso2 === selectedCountry”,我希望我的组件中的那个选项立即出现。但是,我不确定如何在组件中使用 .openPopup 方法。我基本上只想在条件“country.countryInfo.iso2 === selectedCountry”为真时出现弹出窗口。

我正在使用 Leaflet JS

标签: javascriptreactjsleafletreact-leaflet

解决方案


要按Circle(以及在满足某些条件时)打开弹出窗口,可以引入以下组件:

function CountryPOI(props) {
  const { selected } = props;
  const ref = useRef(null);

  useEffect(() => {
    if (selected) {
      ref.current.openPopup();
    }
  });

  return (
    <Circle ref={ref} {...props} >
      <Popup position={props.center}>{props.name}</Popup>
    </Circle>
  );
}

其中selectedprop 确定弹出窗口是否应该打开。

以下示例显示如何为第一项打开弹出窗口:

<CountryPOIs data={data} selectedIndex={0} />

其中CountryPOIs组件呈现标记列表(圆圈):

function CountryPOIs({ data, selectedIndex }) {
  return data.map((item, i) => (
    <CountryPOI
      key={i}
      selected={i === selectedIndex}
      center={[item.position.lat, item.position.lng]}
      fillOpacity={0.5}
      radius={100000}
      name={item.name}
    ></CountryPOI>
  ));
}

这是一个现场演示,演示了如何在选择选项时打开弹出窗口。


推荐阅读