快速入门
🌐 Quick Start
本页面将带你在几分钟内从零到一个可运行的 React Flow 应用。如果你只是想随便看看并了解 React Flow 的情况,可以查看我们的互动式无代码 Playground 。
🌐 This page will take you from zero to a working React Flow app in a few minutes. If you just want to have a look around and get an impression of React Flow, check out our interactive no-code Playground .
安装
🌐 Installation
首先,以你喜欢的方式启动一个新的 React 项目——我们推荐使用 Vite
🌐 First, spin up a new React project however you like — we recommend using Vite
npm init vite my-react-flow-app -- --template react进入你的新项目文件夹 cd 并添加 @xyflow/react 作为依赖
🌐 Next cd into your new project folder and add
@xyflow/react as a dependency
npm install @xyflow/react最后,启动开发服务器,一切就绪!
🌐 Lastly, spin up the dev server and you’re good to go!
用法
🌐 Usage
我们将从 @xyflow/react 包中渲染 <ReactFlow /> 组件。除此之外,还需要定义一些 节点 对象、边 对象和 事件处理程序,这些就是启动所需的全部内容!清空 App.jsx 中的所有内容,然后添加以下内容:
🌐 We will render the <ReactFlow /> component from the
@xyflow/react package. That and defining a handful of node
objects, edge objects and
event handlers are all we need to get
something going! Get rid of everything inside App.jsx and add the following:
import { useState, useCallback } from 'react';
import { ReactFlow, applyNodeChanges, applyEdgeChanges, addEdge } from '@xyflow/react';
import '@xyflow/react/dist/style.css';
const initialNodes = [
{ id: 'n1', position: { x: 0, y: 0 }, data: { label: 'Node 1' } },
{ id: 'n2', position: { x: 0, y: 100 }, data: { label: 'Node 2' } },
];
const initialEdges = [{ id: 'n1-n2', source: 'n1', target: 'n2' }];
export default function App() {
const [nodes, setNodes] = useState(initialNodes);
const [edges, setEdges] = useState(initialEdges);
const onNodesChange = useCallback(
(changes) => setNodes((nodesSnapshot) => applyNodeChanges(changes, nodesSnapshot)),
[],
);
const onEdgesChange = useCallback(
(changes) => setEdges((edgesSnapshot) => applyEdgeChanges(changes, edgesSnapshot)),
[],
);
const onConnect = useCallback(
(params) => setEdges((edgesSnapshot) => addEdge(params, edgesSnapshot)),
[],
);
return (
<div style={{ width: '100vw', height: '100vh' }}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
fitView
/>
</div>
);
}这里有两点需要注意:
🌐 There are two things to pay attention to here:
- 你必须导入 CSS 样式表以使 React Flow 正常工作。
-
<ReactFlow />组件必须有一个具有宽度和高度的父元素。
结果
🌐 Result
瞧,这样你已经创建了你的第一个互动流程!
后续步骤
🌐 Next steps