我尝试初始化第三方库在 React 钩子中我正在使用 useEffect 但我总是得到null 我尝试使用自定义钩子但我得到相同的结果(null)
任何想法?
这是我的代码https://stackblitz.com/edit/react-rg9uov
谢谢
我尝试初始化第三方库在 React 钩子中我正在使用 useEffect 但我总是得到null 我尝试使用自定义钩子但我得到相同的结果(null)
任何想法?
这是我的代码https://stackblitz.com/edit/react-rg9uov
谢谢
您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]);
You're seeing null
because the console.log
is running before useEffect
, if you put a console.log
at the end of useEffect
you'll see that Konva is initialized properly.