数据边缘
🌐 Data Edge
显示源节点 data 对象中一个字段的边。
🌐 An edge that displays one field from the source node’s data object.
Dependencies:
@xyflow/react安装
在安装组件之前,务必遵循 先决条件 。
npx shadcn@latest add https://ui.reactflow.dev/data-edge用法
1. 将组件复制到你的应用中
import { Handle, NodeProps, Position, useReactFlow, Node } from "@xyflow/react";
import { memo } from "react";
import { BaseNode, BaseNodeContent } from "@/components/base-node";
import { Slider } from "@/components/ui/slider";
export type CounterNodeType = Node<{ value: number }>;
export const CounterNode = memo(({ id, data }: NodeProps<CounterNodeType>) => {
const { updateNodeData } = useReactFlow();
return (
<BaseNode>
<BaseNodeContent className="p-5">
<Slider
value={[data.value]}
min={0}
max={100}
step={1}
className="nopan nodrag w-24"
onValueChange={([value]) => {
updateNodeData(id, (node) => ({
...node.data,
value,
}));
}}
/>
<Handle type="source" position={Position.Bottom} />
</BaseNodeContent>
</BaseNode>
);
});2. Connect the component with your React Flow application.
import { Background, ReactFlow } from "@xyflow/react";
import { CounterNode, type CounterNodeType } from "./component-example";
import { DataEdge } from "@/registry/components/data-edge/";
const defaultNodes = [
{
id: "1",
position: { x: 100, y: 100 },
type: "counterNode",
data: { value: 10 },
},
{
id: "2",
position: { x: 300, y: 300 },
data: { label: "Output" },
},
];
const nodeTypes = {
counterNode: CounterNode,
};
const defaultEdges = [
{
id: "1->2",
source: "1",
target: "2",
type: "dataEdge",
data: { key: "value" },
} satisfies DataEdge<CounterNodeType>,
];
const edgeTypes = {
dataEdge: DataEdge,
};
export default function App() {
return (
<div className="h-full w-full">
<ReactFlow
defaultNodes={defaultNodes}
nodeTypes={nodeTypes}
defaultEdges={defaultEdges}
edgeTypes={edgeTypes}
fitView
>
<Background />
</ReactFlow>
</div>
);
}附加类型安全
🌐 Additional type safety
在创建这种类型的新边时,你可以使用 TypeScript 的 satisfies 谓词以及应用中节点的特定类型,以确保边数据的 key 属性是节点数据的有效键。
🌐 When creating new edges of this type, you can use TypeScript’s satisfies predicate
along with the specific type of a node in your application to ensure the key
property of the edge’s data is a valid key of the node’s data.
type CounterNode = Node<{ count: number }>;
const initialEdges = [
{
id: 'edge-1',
source: 'node-1',
target: 'node-2',
type: 'dataEdge',
data: {
key: 'count',
} satisfies DataEdge<CounterNode>,
},
];如果你尝试使用节点数据中不存在的键,TypeScript 会显示如下错误信息:
🌐 If you try to use a key that is not present in the node’s data, TypeScript will show an error message like:
ts: 类型 ‘“value”’ 不能赋值给类型 ‘“count”’。
Last updated on