快速入门
¥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
将 Next 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 />
组件。只需定义一些 node 对象、edge 对象和 事件处理程序 对象,我们就可以开始使用了!删除 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 正常工作。
¥
You must import the css stylesheet for React Flow to work.<ReactFlow />
组件必须具有一个具有宽度和高度的父元素。
¥<ReactFlow />
component must have a parent element with a
width and height.
结果
¥Result
瞧。你已经创建了第一个交互式流程!
¥Et voila. You’ve already created your first interactive flow!
后续步骤
¥Next steps