使用 useEffect 在 React 中运行 cytoscape

Sex*_*yMF 1 cytoscape reactjs

我有以下简单的代码:

export const App = () => {
  useEffect(() => {
    const config = {
      container: document.getElementById("cy"),
      style: [
        {
          selector: "node",
          style: { content: "data(id)" }
        }
      ],
      elements: [
        { data: { id: "n1" } },
        { data: { id: "n2" } },
        { data: { id: "e1", source: "n1", target: "n2" } }
      ]
    };
    cytoscape(config);
  }, []);
  return <div id="cy" />;
};

Run Code Online (Sandbox Code Playgroud)

该页面为空.... https://stackblitz.com/edit/react-ts-vo5hv6

我该如何解决这个问题?

谢谢

wie*_*son 5

查看 useRef 挂钩(https://reactjs.org/docs/hooks-reference.html#useref),而不是直接使用 document.getElementById("cy") 。看起来您还需要为容器元素设置高度,否则它不可见。

Refs 提供了一种访问 DOM 节点或在 render 方法中创建的 React 元素的方法。

export default function App() {
  const containerRef = useRef();

  useEffect(() => {
    const config = {
      container: containerRef.current,
      style: [
        {
          selector: "node",
          style: { content: "data(id)" },
        },
      ],
      elements: [
        { data: { id: "n1" } },
        { data: { id: "n2" } },
        { data: { id: "e1", source: "n1", target: "n2" } },
      ],
    };

    cytoscape(config);
  }, []);

  return (
    <div>
      <h1>Hello cytoscape</h1>
      <div ref={containerRef} style={{ height: "300px" }} />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)