状态会在使用React Image Mapper双击时更新

问题描述 投票:0回答:1

我在使用react image mapper库时遇到了一些小问题。

[我的地图上放置了一个初始圆,每当我单击另一个区域时,点都会移动。我通过更新现有点来做到这一点。发生的事情是,我必须单击两次地图才能移动它。我以为库没问题,我的状态更新功能不正确?

import React, { useState, useCallback } from "react";
import ImageMapper from "react-image-mapper";
import "./styles.css";

export default function App() {
  const [mapAreas, setMapAreas] = useState({
    name: "my-map",
    areas: [
      { id: 5, shape: "circle", coords: [170, 100, 10], preFillColor: "#fff" }
    ]
  });

  const getTipPosition = area => {
    const obj = { top: `${area.center[1]}px`, left: `${area.center[0]}px` };
    console.log(obj);
  };

  const handleUpdateMapArea = useCallback(
    evt =>
      updateMapArea(5, [evt.nativeEvent.layerX, evt.nativeEvent.layerY, 10]),
    []
  );

  const updateMapArea = (id, coords) => {
    console.log(id, coords);
    const areas = mapAreas.areas.map(item =>
      item.id === id ? { ...item, coords } : item
    );
    setMapAreas({
      name: mapAreas.name,
      areas
    });
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <ImageMapper
        src="https://c1.staticflickr.com/5/4052/4503898393_303cfbc9fd_b.jpg"
        onClick={area => getTipPosition(area)}
        onImageClick={handleUpdateMapArea}
        map={mapAreas}
        width={500}
      />
      <pre>On each click, circle should be position of the clicked</pre>
    </div>
  );
}

DEMO

我尝试过不使用useCallback,但完全一样。

reactjs
1个回答
0
投票

[This comment已经回答了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.