临时边缘
在 React Flow 中,几乎所有东西都是围绕节点和边的概念构建的。边是节点之间的连接,但如果我们想创建一条只连接到一个节点的边怎么办?那么完全不连接任何节点的“边”呢?
🌐 In React Flow, almost everything is built around the concepts of nodes and edges. Edges are the connections between nodes, but what if we want to create an edge that is only connected to one node? What about an “edge” not connected to any nodes at all?
此示例显示了当用户释放连接线而未建立连接时,如何创建“未完成”的边。在释放连接线的位置会渲染一个虚节点,并将临时边添加到流程中。利用可编辑边,用户可以重新拾起该边并完成连接,此时虚节点将被移除!
🌐 This example shows how to create an “incomplete” edge when a user releases a connection line without making a connection. A ghost node is rendered where the connection line was released, and a temporary edge is added to the flow. Making use of editable edges, the user can pick the edge back up and complete the connection at which point the ghost node is removed!
不要直接将 A 连接到流程中的 B,尝试在空白处释放连接线以创建一个临时边!
import {
Background,
ReactFlow,
ReactFlowProvider,
useNodesState,
useEdgesState,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import { GhostNode, useIncompleteEdge } from './useIncompleteEdge';
const nodeTypes = {
ghost: GhostNode,
};
const initialNodes = [
{ id: '0', type: 'input', data: { label: 'A' }, position: { x: 0, y: -100 } },
{ id: '1', type: 'output', data: { label: 'B' }, position: { x: 0, y: 100 } },
];
const IncompleteEdge = () => {
const [nodes, , onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState([]);
const handlers = useIncompleteEdge();
return (
<ReactFlow
nodes={nodes}
nodeTypes={nodeTypes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
fitView
{...handlers}
>
<Background />
</ReactFlow>
);
};
export default () => (
<ReactFlowProvider>
<IncompleteEdge />
</ReactFlowProvider>
);我们定义了一个 useIncompleteEdge 钩子,它封装了创建和管理“幽灵节点”的逻辑。它返回多个事件处理程序,旨在传递给 <ReactFlow /> 组件。
🌐 We’ve defined a useIncompleteEdge hook that encapsulates the logic for creating
and managing a “ghost node”. It returns a number of event handlers intended to be
passed to the <ReactFlow /> component.
onConnect在建立完整连接时被调用。onConnectEnd会在用户释放连接线时被调用。第二个connectionState参数可用于确定连接是否成功,以及它的起点位置(如果连接有效,也包括终点)。此回调会创建一个幻影节点,并从connectionState.fromNode.id到该幻影节点创建一条临时边。该临时边被标记为reconnectable,以便用户可以重新拾取它并完成连接。[onReconnect](/api-reference/react-flow#onreconnect)会在完全重新连接时被调用。onReconnectEnd会在用户释放重新连接线时被调用。此回调会移除虚节点和临时边。onConnectEnd被调用时,可能会重新添加一个新的。
这个示例是我们在边上添加节点并放置示例的改编!