我正在使用 react-konva,其中我有一个包含所有 konva 对象的数组,并且我有一个函数可以将所选对象带到该数组的前面或后面,以在我的 kanvas 上创建图层。
当我触发此函数时,数组中对象的顺序工作正常,但所有对象的变换更改都丢失了,我该怎么做才能在数组更改期间不丢失此参数?
changeOrderArray = (front) => {
let { arrayObjectsLayer, selectedObject } = this.state;
front ?
arrayObjectsLayer.push(
arrayObjectsLayer.splice(
arrayObjectsLayer.findIndex(
elt => elt.id === selectedObject.id),
1)[0]
)
: arrayObjectsLayer.unshift(
arrayObjectsLayer.splice(
arrayObjectsLayer.findIndex(
elt => elt.id === selectedObject.id),
1)[0]
)
this.setState({
arrayObjectsLayer
});
}
循环
arrayObjectsLayer.map((item, index) => {
return (
item.type === 'square' ?
<RectanguleComponent
shapeProps={item}
isSelected={
selectedObject && item.id === selectedObject.id
}
onSelect={() => {
this.selectShape(item);
}}
onChange={newAttrs => {
const item = arrayObjectsLayer.slice();
item[index] = newAttrs;
this.setArrayObject(item);
}}
/>
:
item.type === 'triangule' ?
<TrianguleComponent
shapeProps={item}
isSelected={
selectedObject && item.id === selectedObject.id
}
onSelect={() => {
this.selectShape(item);
}}
onChange={newAttrs => {
const item = arrayObjectsLayer.slice();
item[index] = newAttrs;
this.setArrayObject(item);
}}
/>
:
etc ...
带变压器的基本组件
export const RectanguleComponent = ({ shapeProps, isSelected, onSelect, onChange }) => {
const shapeRef = React.useRef();
const trRef = React.useRef();
React.useEffect(() => {
if (isSelected) {
trRef.current.setNode(shapeRef.current);
trRef.current.getLayer().batchDraw();
}
}, [isSelected]);
return (
<React.Fragment>
<Rect
onClick={onSelect}
ref={shapeRef}
{...shapeProps}
draggable
onDragEnd={e => {
onChange({
...shapeProps,
x: e.target.x(),
y: e.target.y()
});
}}
onTransformEnd={e => {
// transformer is changing scale
const node = shapeRef.current;
const scaleX = node.scaleX();
const scaleY = node.scaleY();
// we will reset it back
node.scaleX(1);
node.scaleY(1);
onChange({
...shapeProps,
x: node.x(),
y: node.y(),
width: node.width() * scaleX,
height: node.height() * scaleY
});
}}
/>
{isSelected && <Transformer ref={trRef} />}
</React.Fragment>
);
};