gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:42:26 27 4
gpt4 key购买 nike

我正在尝试使用 ReactJS 创建一个图形编辑器。我有我的 Workspace组件。此组件使用 Canvas 绘制对象。 Workspace组件是一个 React 类组件。
我无法获取 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>
)
}
}

最佳答案

如果你从上到下阅读你的代码,那么 Canvas 元素在 render 之前还不存在。方法已被调用。因此,您必须等待组件实际渲染一次才能创建上下文。
更具体地说,等待 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>
)
}
}

关于javascript - 无法使用 refs 从 render() 方法获取 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490135/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com