我正在查看以下代码:
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import backImg from "./background.png";
const Canvas = props => {
const canvas = useRef(null);
const image = useRef(null);
useEffect(() => {
const ctx = canvas.current.getContext("2d");
image.current.onload = () => {
ctx.drawImage(image.current, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(props.text, 210, 75);
};
}, []);
useEffect(() => {
const ctx = canvas.current.getContext("2d");
ctx.drawImage(image.current, 0, 0);
ctx.font = "40px Courier";
ctx.fillText(props.text, 210, 75);
});
return (
<div>
<canvas ref={canvas} width={640} height={425} />
<img
ref={image}
alt="Stackoverflow56203352"
src={backImg}
className="hidden"
/>
</div>
);
};
function App() {
return (
<div className="App">
<Canvas text="TEST 123" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
完整的沙盒代码为here
我有以下问题:
(1)在何处调用image
useRef
(2)两个useEffect
代码具有相同的代码,除了第一个在函数调用中被调用