问题描述
我有一个引用画布元素的类组件,但是当我尝试在功能组件中引用同一元素时,就会遇到问题。
class Game extends Component {
state = {
circle: {
x: 50,y: 100,radius: 20
}
}
draw = () => {
const ctx = this.refs.canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(this.state.circle.x,this.state.circle.y,this.state.circle.radius,2 * Math.PI);
ctx.fill();
ctx.stroke();
}
componentDidMount() {
this.draw()
}
render() {
return (
<div>
<canvas ref="canvas" width={450} height={650} />
</div>
);
}
}
canvas.height是NaN,我不完全理解为什么我需要使用.current来访问DOM元素。
const Game = () => {
const canvas = useRef(null);
const [circle,setcircle] = useState({
x: 50,y: canvas.height/2,radius: 20
});
useEffect(() => {
draw()
},[]);
const draw = () => {
const ctx = canvas.current.getContext("2d");
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,2 * Math.PI);
ctx.fill();
ctx.stroke();
}
return (
<div>
<canvas ref={canvas} width={450} height={650} />
</div>
);
}
解决方法
尝试
const [circle,setcircle] = useState({
x: 50,// y: canvas.current.height/2,// cannot determine it here,as the commit has not happned
radius: 20,});
useLayoutEffect(() => {
setcircle({
x: 50,y: canvas.current.height / 2,radius: 20,});
},[]);