useReactFlow()
此钩子返回一个 ReactFlowInstance,可用于更新节点和边、操作视口,或查询流的当前状态。
🌐 This hook returns a ReactFlowInstance that can
be used to update nodes and edges, manipulate the viewport, or query the current
state of the flow.
import { useCallback, useState } from 'react';
import { useReactFlow } from '@xyflow/react';
export function NodeCounter() {
const reactFlow = useReactFlow();
const [count, setCount] = useState(0);
const countNodes = useCallback(() => {
setCount(reactFlow.getNodes().length);
// you need to pass it as a dependency if you are using it with useEffect or useCallback
// because at the first render, it's not initialized yet and some functions might not work.
}, [reactFlow]);
return (
<div>
<button onClick={countNodes}>Update count</button>
<p>There are {count} nodes in the flow.</p>
</div>
);
}签名
🌐 Signature
Parameters:This function does not accept any parameters.
Returns:TypeScript
这个 hook 接受自定义节点和边类型的通用类型参数。有关更多信息,请参阅我们 TypeScript 指南中的这一部分。
🌐 This hook accepts a generic type argument of custom node & edge types. See this section in our TypeScript guide for more information.
const reactFlow = useReactFlow<CustomNodeType, CustomEdgeType>();注释
🌐 Notes
- 此 Hook 只能在
<ReactFlowProvider />或<ReactFlow />组件的子组件中使用。 - 与
useNodes或useEdges不同,这个 hook 在状态改变时不会导致你的组件重新渲染。相反,你可以通过使用这个 hook 返回的ReactFlowInstance上的方法在需要时查询状态。
Last updated on