【问题标题】:How to get a hold of the html element defined through React JSX?如何获取通过 React JSX 定义的 html 元素?
【发布时间】: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 元素,因此我不能只在其上调用 getContextthis.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;
}

【问题讨论】:

  • 我不明白这个问题。你想在父组件中使用&lt;canvas&gt; jsx 元素的引用吗?
  • 我想在渲染中获取 HTML 元素画布。您可以使用componentDidMount 中的参考来获得它。但是,我问我是否应该能够在渲染函数中得到它。

标签: javascript reactjs jsx


【解决方案1】:

所以只有在渲染之后才能获取上下文,所以基本上流程是构造函数,componentWillMount(Unsafe method),渲染和最后一个componentDidMount。您可以通过调用 componentDidMount 在渲染后获取上下文,并且可以在渲染后更新它

您可以查看以下代码

class Canvas extends Component {
  componentDidMount() {
    let canvas = this.refs.canvas;
    const ctx = canvas.getContext("2d");
    ctx.fillRect(0, 0, 100, 100);
    // after render 
    console.log(canvas.getContext("2d"));
  }
  render() {
    let width, height;
    width = height = window.innerHeight - 50;
    let canvas = <canvas ref="canvas" width={width} height={height} />;
    return canvas;
  }
}

export default Canvas;

Codepen

【讨论】:

  • 所以您是说在渲染完成执行之前不会创建 HTML 元素?这就是为什么只有在渲染完成运行后才能在componentDidMount 中获取 HTML 元素的原因?
  • 是的,所以当你在 render 中编写一个 jsx 元素时,它基本上调用 React.renderElement(),你可以在这里阅读更多内容reactjs.org/docs/rendering-elements.html
猜你喜欢
  • 2015-01-29
  • 2021-12-11
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多