0

我正在使用react-konva,并且我有两个Circle想要连接的组件Line。我已经通过硬编码实现了这一点,但我想让它具有交互性。

我的目标:当我单击一个Circle组件时,它会创建一个Line组件。然后,如果我点击另一个Circle,两者都会被连接Line

我的问题:我不知道该怎么做。我对想法持开放态度。

4

1 回答 1

2

有很多方法可以实现它。你可以这样做:

import React from "react";
import { render } from "react-dom";
import { Stage, Layer, Circle, Line, Text } from "react-konva";

function generateShapes() {
  const shapes = [];
  for (var i = 0; i < 10; i++) {
    shapes.push({
      id: i,
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight
    });
  }
  return shapes;
}

const INITIAL_SHAPES = generateShapes();

const App = () => {
  const [shapes, setShapes] = React.useState(INITIAL_SHAPES);
  const [connectors, setConnectors] = React.useState([]);

  const [fromShapeId, setFromShapeId] = React.useState(null);

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        {connectors.map(con => {
          const from = shapes.find(s => s.id === con.from);
          const to = shapes.find(s => s.id === con.to);

          return (
            <Line
              key={con.id}
              points={[from.x, from.y, to.x, to.y]}
              stroke="black"
            />
          );
        })}
        {shapes.map(shape => (
          <Circle
            x={shape.x}
            y={shape.y}
            key={shape.id}
            fill={fromShapeId === shape.id ? "red" : "green"}
            radius={20}
            shadowBlur={10}
            onClick={() => {
              if (fromShapeId) {
                const newConnector = {
                  from: fromShapeId,
                  to: shape.id,
                  id: connectors.length
                };
                setConnectors(connectors.concat([newConnector]));
                setFromShapeId(null);
              } else {
                setFromShapeId(shape.id);
              }
            }}
          />
        ))}
        <Text text="Click on on circle then on another to connect them" />
      </Layer>
    </Stage>
  );
};

render(<App />, document.getElementById("root"));

演示:https ://codesandbox.io/s/react-konva-connecting-shapes-demo-usr05

于 2019-12-04T13:47:25.610 回答