如何解决无法使用refs从render方法获取HTML元素
我正在尝试使用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>
)
}
}
解决方法
this.canvasRef
仅可在componentDidMount中访问
componentDidMount called BEFORE ref callback被接受的答案将为您提供更多信息。美好的一天!
如果从上至下阅读代码,则在调用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>
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。