2

我正在尝试使用 ReactJS 创建一个图形编辑器。我有我的Workspace组件。这个组件使用画布绘制对象。该Workspace组件是一个 React 类组件。我无法获取render()方法中的 HTML 元素。

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

我有这样的错误:

TypeError:无法读取 null 的属性“getContext”

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>
        )
    }
}
4

2 回答 2

1

this.canvasRef将仅在 componentDidMount componentDidMount 在 ref 回调之前调用,接受的答案将为您提供更多信息。愉快的一天!

于 2020-10-22T20:36:24.053 回答
1

如果您从上到下阅读代码,那么在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>
        )
    }
}
于 2020-10-22T20:38:28.177 回答