访问元素高度时,在功能组件中使用Ref会导致NaN

问题描述

我有一个引用画布元素的类组件,但是当我尝试在功能组件中引用同一元素时,就会遇到问题。

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,});
},[]);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...