Reactjs 在启动点击功能之前,如何确保ref.current存在?
尝试将canvasRef.current设置为当前时,我收到一个未定义的错误。我尝试了许多不同的方法来形成回调引用,但我没有得到任何运气。在canvasRef.current未定义后,如何等待启动onClick函数“handleViewStuff”Reactjs 在启动点击功能之前,如何确保ref.current存在?,reactjs,Reactjs,尝试将canvasRef.current设置为当前时,我收到一个未定义的错误。我尝试了许多不同的方法来形成回调引用,但我没有得到任何运气。在canvasRef.current未定义后,如何等待启动onClick函数“handleViewStuff” const Child = (props) => { const canvasRef = useRef(); const handleViewStuff = useCallback(() => { apiC
const Child = (props) => {
const canvasRef = useRef();
const handleViewStuff = useCallback(() => {
apiCall(id)
.then((response) => {
// do stuff
return stuff;
})
.then((result) => {
result.getPage().then((page) => {
const canvas = canvasRef.current;
const context = canvas.getContext('2d'); // error is coming in here as getContext of undefined meaning canvas is undefined'
canvas.height = 650;
const renderContext = {
canvasContext: context,
};
page.render(renderContext);
});
});
}, []);
return (
<Fragment>
<canvas ref={(e) => {canvasRef.current = e}} />
<Button
onClick={handleViewStuff}
>
View Stuff
</Button>
</Fragment>
);
};
export default Child;
const Child=(道具)=>{
const canvasRef=useRef();
const handleViewStuff=useCallback(()=>{
apiCall(id)
。然后((响应)=>{
//做事
归还物品;
})
。然后((结果)=>{
result.getPage()。然后((页面)=>{
const canvas=canvasRef.current;
const context=canvas.getContext('2d');//此处出现错误,因为未定义意义的getContext canvas未定义'
高度=650;
常量renderContext={
背景:背景,
};
page.render(renderContext);
});
});
}, []);
返回(
{canvasRef.current=e}}/>
查看资料
);
};
导出默认子对象;
if语句
可选链接
useCallback
...
if(canvas.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
}
...
const canvas = canvasRef?.current;
const context = canvas?.getContext('2d');
const handleViewStuff = useCallback(() => {
...
}, [canvasRef.current]);
<canvas ref={canvasRef} />