React-Typescript如何写Canvas
参考文档 – 需要翻墙
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import React, { useRef, useEffect } from 'react';
const SimpleCanvasExample: React.FC<{}> = () => { let canvasRef = useRef<HTMLCanvasElement | null>(null); let canvasCtxRef = React.useRef<CanvasRenderingContext2D | null>(null);
useEffect(() => { if (canvasRef.current) { canvasCtxRef.current = canvasRef.current.getContext('2d'); let ctx = canvasCtxRef.current; ctx!.beginPath(); ctx!.arc(95, 50, 40, 0, 2 * Math.PI); ctx!.stroke(); } }, []);
return <canvas ref={canvasRef}></canvas>; };
export default SimpleCanvasExample;
|
类型完整的React.forwardRef写法
需求:一个评论用的窗口,通过forwardRef传递方法给父组件调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| export type CommentHandler = { openDrawer: () => void closeDrawer: () => void }
const CommentDrawer: React.ForwardRefRenderFunction<CommentHandler, IProps> = (props,ref)=>{
const openDrawer = ()=>{}; const closeDrawer = ()=>{}; useImperativeHandle(ref, () => { return { openDrawer, closeDrawer, } }) return <div></div> }
export default forwardRef(CommentDrawer)
|
使用
1 2
| const ref = useRef<React.ElementRef<typeof CommentDrawer>>(null) ref.current?.openDrawer()
|