首页 > 解决方案 > Konva onDragMove 和 onDragEnd 不更新位置?

问题描述

我正在尝试 onDragMove 手动更新元素位置。形状本身正在拖动,并且正在更新对象,但它没有被渲染?

与 onDragEnd 相同。两者都正确更新了形状数组,但它没有出现在渲染中,即使

import React, { useState, useEffect } from "react";
import { Stage, Layer, Rect } from "react-konva";
import "./styles.css";

export default function App() {
  const [objects, setObject] = useState([{ id: "rect1", x: 50, y: 50 }]);

  // Function
  const updatePosition = (id) => {
    let update = objects.map((entry) => {
      if (entry.id !== id) return entry;
      else return { ...entry, x: 100, y: 0 };
    });

    setObject(update);
  };

  // We can see the object is updated with the new coords
  useEffect(() => {
    console.log(objects);
  });

  return (
    <main style={{ background: "lightgrey" }}>
      <Stage width={800} height={800}>
        <Layer>
          {objects.map((object) => {
            // This shows an updated X value correclty
            console.log(object.x);

            // It doesn't render the new x position at all
            return (
              <Rect
                key={object.id}
                fill={"green"}
                width={200}
                height={300}
                x={object.x}
                y={object.y}
                draggable
                onDragMove={() => updatePosition(object.id)}
                onDragEnd={() => updatePosition(object.id)}
              />
            );
          })}
        </Layer>
      </Stage>
    </main>
  );
}

https://codesandbox.io/s/priceless-dust-cjr6z?file=/src/App.js:0-1323

标签: konvajsreact-konvakonvakonvajs-reactjs

解决方案


从您的演示中,我看到您正在为形状设置相同的 {x, y} 位置:

const updatePosition = (id) => {
    let update = objects.map((entry) => {
      if (entry.id !== id) return entry;
      else return { ...entry, x: 100, y: 0 };
    });

    setObject(update);
};

默认情况下react-konva只会设置100, 0一次位置。在下一次渲染调用中,<Rect />元素的属性不会改变。react-konva将仅更新以前渲染属性的 CHANGED。

如果要严格设置最后一个属性,则应使用严格模式


推荐阅读