如何在反应钩子中初始化第三方库(konvajs)

how initialize third party library (konvajs) in react hooks

我尝试在 React hooks 中初始化第三方库我正在使用 useEffect 但我总是得到 null 我尝试使用自定义挂钩,但得到了相同的结果 (null)

有什么想法吗?

这是我的代码https://stackblitz.com/edit/react-rg9uov

谢谢

你看到 null 因为 console.loguseEffect 之前是 运行,如果你把 console.log 放在 [=12] 的末尾=] 您会看到 Konva 已正确初始化。

您的 useEffect 应该为 ref 声明依赖数组,也不确定为什么使用 const stage = useRef(null);stage 可能只是一个组件状态。

 const [stage, setStage] = React.useState();
 const ref = useRef();

 useEffect(() => {
    if(ref.current){
      setStage(new Konva.Stage({
      container: ref.current, // id of container <div>
      width: 500,
      height: 300
    }))
    }

  },[ref]);