【发布时间】:2019-12-02 07:12:29
【问题描述】:
考虑这个组件,
import React, { Component } from 'react';
class Canvas extends Component {
componentDidMount() {
let canvas = this.refs.canvas;
const ctx = canvas.getContext('2d');
ctx.fillRect(0,0, 100, 100);
}
render() {
let width, height;
width = height = window.innerHeight - 50;
let canvas = <canvas ref="canvas" width={width} height={height} />;
// canvas.getContext('2d') does not work here
// this.refs is also empty: {}
return canvas;
}
}
export default Canvas;
观察我们如何使用this.refs 获取componentDidMount 中的实际HTML 元素,然后在其上调用它的方法getContext。我的印象是,如果我们将 JSX 分配给像这里这样的变量,
let canvas = <canvas ref="canvas" width={width} height={height} />;
我们得到了 JSX 返回的实际 HTML 元素。情况似乎并非如此,因为这里的变量 canvas 是一个 React 组件而不是 HTML 元素,因此我不能只在其上调用 getContext。 this.refs后面的定义也是空的。
我想知道是否有一种方法可以在通过 JSX 定义后获取实际的 HTML 元素并能够在其上调用它的函数?或者,这是一个坏主意吗?我想在上述组件的渲染中做这样的事情,
render() {
let width, height;
width = height = window.innerHeight - 50;
let canvas = <canvas ref="canvas" width={width} height={height} />;
const ctx = canvas.getContext('2d');
ctx.fillRect(0,0, 100, 100);
return canvas;
}
【问题讨论】:
-
我不明白这个问题。你想在父组件中使用
<canvas>jsx 元素的引用吗? -
我想在渲染中获取 HTML 元素画布。您可以使用
componentDidMount中的参考来获得它。但是,我问我是否应该能够在渲染函数中得到它。
标签: javascript reactjs jsx