getting react-konva context in a parent handler - is there a better way than my code below?

Viewed 67

Is there a better way, that is: (a) having to pass the child event back to the parent to be able to extract the stage/layer to then be able to do a konva node "find", and (b) having to "find" nodes using this approach (as using Konva-React JSX I don't have references to them in the code)

import { Stage, Layer, Text } from "react-konva";
import { KonvaEventObject } from "konva/lib/Node";

// ----------------------------------------------
type TestTileProps = {
  id: String;
  hodh: (e: KonvaEventObject<DragEvent>) => void;
};

const TestTile = function ({ id, hodh }: TestTileProps) {
  const handleOnDragMove = (e: KonvaEventObject<DragEvent>) => {
    hodh(e);
  }; 
  return (
    <Text
      y={20}
      text={id + "  <=="}
      draggable={true}
      onDragMove={handleOnDragMove}
    />
  );
};
// ----------------------------------------------
const App = () => {

  const higherOrderDragHandler = (e: KonvaEventObject<DragEvent>) => {
    const layer = e.target.getLayer();
    const textNode = layer.find(".MainText")[0];
    textNode.position({
      x: e.target.position().y,
      y: textNode.position().y
    });
    
  };

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Text name="MainText" text="Heading 123" />
        <TestTile id={"Value pass"} hodh={higherOrderDragHandler} />
      </Layer>
    </Stage>
  );
};

export default App;

// ----------------------------------------------
0 Answers
Related