【问题标题】:refs in reactjs Component emptyreactjs组件中的refs为空
【发布时间】:2018-10-02 04:38:24
【问题描述】:

我的渲染函数中有一个 react-chartjs-2 元素,我从 React.createRef() 分配了一个引用,但是

  1. 引用为空
  2. 我的 ref 上的当前属性为 null

    import React, { Component } from 'react';
    const LineChart = require('react-chartjs-2').Line;
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.chartRef = React.createRef();
        this.chartObject = null;
      }
    
      componentDidMount() {
        this.chartObject = this.chartRef.current.getContext('2d');
        this.chartObject.update();
      }
    
      render() {
    
        return ( 
          <div className = "App">
            <LineChart 
              data = {}
              width = {600}
              height = {250}
              ref = {this.chartRef}/>
            </div>
          );
        }
      }
    

【问题讨论】:

  • 你在使用 React 16.3 吗?
  • 是的,我使用的是 16.3 (16.3.2)

标签: reactjs chart.js


【解决方案1】:

来自React docs

当 ref 属性用于 自定义类组件,ref对象接收挂载的实例 组件的当前位置。

所以你不会收到canvas,而是一个组件实例何时它会挂载。这就是为什么我认为当 App componentDidMount 被调用时,LineChart 尚未安装,这就是为什么 current 仍然为空。

再次

this.chartObject = this.chartRef.current.getContext('2d');

将不起作用,因为您将收到一个组件实例,而不是 canvas

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2018-11-25
    • 1970-01-01
    • 2016-08-10
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多