无法使用 refs 从 render() 方法获取 HTML 元素

Cannot get an HTML element from the render() method using refs

我正在尝试使用 ReactJS 创建一个图形编辑器。我的 Workspace component.This 组件使用 canvas 绘制对象。 Workspace 组件是 React class 组件。 我无法获得 HTML 元素,它位于 render() 方法中。

我无法使用 document.getElementById(..),我决定使用 React Refs。这更像是干净的。

我遇到了这样的错误:

TypeError: Cannot read property 'getContext' of null

import React, { Component } from 'react';
import './Workspace.css';

// Workspace component is resposiable for drawing defferent elements on the screen
// It uses canvas API to draw elements and the stuff like that
export default class Workspace extends Component {

    constructor(props) {

        // Calling parent`s constructor function
        super(props);

        // All objects that will be drawn
        this.objects = [];

        // Creating the `canvasRef` ref for having access to the canvas element
        this.canvasRef = React.createRef();

        // Getting the canvas element, using the`canvasRef` ref
        const canvas = this.canvasRef.current;

        // Creating context
        this.context = canvas.getContext('2d');

    }

    render() {
        return (
            <div className="workspace">
                <canvas className="canvas" ref={this.canvasRef}></canvas>
            </div>
        )
    }
}

this.canvasRef 将只能在 componentDidMount 中访问 接受的答案将为您提供更多信息。美好的一天!

如果您从上到下阅读代码,那么在调用 render 方法之前 canvas 元素还不存在。所以你必须等待组件实际渲染一次来创建你的上下文。

更具体地说,等待调用 componentDidMount 方法,然后在其中创建上下文。

import React, { Component } from 'react';
import './Workspace.css';

// Workspace component is resposiable for drawing defferent elements on the screen
// It uses canvas API to draw elements and the stuff like that
export default class Workspace extends Component {

    constructor(props) {

        // Calling parent`s constructor function
        super(props);

        // All objects that will be drawn
        this.objects = [];

        // Creating the `canvasRef` ref for having access to the canvas element
        this.canvasRef = React.createRef();
    }

    componentDidMount() {
        // Getting the canvas element, using the`canvasRef` ref
        const canvas = this.canvasRef.current;

        // Creating context
        this.context = canvas.getContext('2d');
    }

    render() {
        return (
            <div className="workspace">
                <canvas className="canvas" ref={this.canvasRef}></canvas>
            </div>
        )
    }
}