参考钩子

useOnSelectionChange

GitHub 源代码

此钩子允许您监听节点和边选择的变化。顾名思义,您提供的回调将在节点或边的选择发生变化时被调用。

您需要记忆传递的 onChange 处理程序,否则钩子将无法正常工作。

import { useState } from 'react';
import { ReactFlow, useOnSelectionChange } from '@xyflow/react';
 
function SelectionDisplay() {
  const [selectedNodes, setSelectedNodes] = useState([]);
  const [selectedEdges, setSelectedEdges] = useState([]);
 
  // the passed handler has to be memoized, otherwise the hook will not work correctly
  const onChange = useCallback(({ nodes, edges }) => {
    setSelectedNodes(nodes.map((node) => node.id));
    setSelectedEdges(edges.map((edge) => edge.id));
  }, []);
 
  useOnSelectionChange({
    onChange,
  });
 
  return (
    <div>
      <p>Selected nodes: {selectedNodes.join(', ')}</p>
      <p>Selected edges: {selectedEdges.join(', ')}</p>
    </div>
  );
}

签名

#参数
#options
对象
#options.onChange
(参数: { nodes: Node[]; edges: Edge[]; }) =>
#返回值

备注