是否可以省略呼叫
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
我每次想在功能或使用效果中引用canvas DOM节点吗?
const drawCanvas = () => {
const canvasRef = React.useRef(null);
const [position, setPosition] = React.useState({});
React.useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, canvas.width, canvas.height);
}, []);
React.useEffect(() => {
const canvas = canvasRef.current;
const x = canvas.width;
const y = canvas.height;
setPosition({ x, y });
}, []);
return <canvas ref={canvasRef} />;
};
我无法将canvasRef.current设置为变量,因为它在第一次迭代时的值为空。
答案 0 :(得分:1)
实际上,您不能将当前参考节点设置为变量。
如果必须在不同的组件中实现相同的逻辑,则可以创建自己的钩子:
const useCanvas = (callback) => {
const canvasRef = React.useRef(null);
React.useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
callback([canvas, ctx]);
}, []);
return canvasRef;
}
const Canvas = () => {
const [position, setPosition] = React.useState({});
const canvasRef = useCanvas(([canvas, ctx]) => {
ctx.fillRect(0, 0, canvas.width, canvas.height);
const x = canvas.width;
const y = canvas.height;
setPosition({ x, y });
});
return (<canvas ref={canvasRef} />);
};
一些评论:
drawCanvas
函数重命名为Canvas
-一种更标准的命名React函数组件的方法