【问题标题】:Konva onDragMove and onDragEnd not updating position?Konva onDragMove 和 onDragEnd 不更新位置?
【发布时间】:2020-12-10 20:50:50
【问题描述】:

我正在尝试 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

【问题讨论】:

  • 沙盒似乎可以工作 - 这仍然是个问题吗?解决方法是什么?

标签: konvajs react-konva konva konvajs-reactjs


【解决方案1】:

从您的演示中,我看到您正在为形状设置相同的 {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 位置。在下一次渲染调用中,&lt;Rect /&gt; 元素的属性不会改变。 react-konva 将仅更新以前的渲染属性更改。

如果要严格设置最后一个属性,应该使用strict mode

【讨论】:

  • 啊,我明白了,我在阅读文档时稍有疏忽。在矩形上使用严格模式,正好解决了我需要的问题。
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2019-04-19
  • 1970-01-01
相关资源
最近更新 更多