konvajs - 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
解决方案
从您的演示中,我看到您正在为形状设置相同的 {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。
如果要严格设置最后一个属性,则应使用严格模式
推荐阅读
- php - 请求明确给定的 IP,但使用明确给定的主机名来进行 SSL 验证?
- php - Drush 允许的内存大小为 2097152 字节已用尽
- r - r studio中的图例符号和文本间距问题
- jsp - 如何将此选中的项目发送到另一个页面上显示?JSP 伺服器
- parameters - 训练 word2vec 时出现内存错误:分层 softmax
- javascript - Angular 2 在 PDF/PNG 上注释
- python - Python:将编译对象添加到 Memcached
- r - 如何通过分隔符分割数据框
- swift - 如何快速获取日期
- python - 如何在 Pandas 上获取每列值的最后 5 行(放弃前的 5 个操作)