reactjs组件中的引用为空

reactjs组件中的引用为空,reactjs,chart.js,Reactjs,Chart.js,我在渲染函数中有一个react-chartjs-2元素,我从react.createRef()为其分配了一个ref,但是 参考文献是空的 my ref上的当前属性为null import React, { Component } from 'react'; const LineChart = require('react-chartjs-2').Line; class App extends Component { constructor(props) { super(props)

我在渲染函数中有一个react-chartjs-2元素,我从react.createRef()为其分配了一个ref,但是

  • 参考文献是空的
  • my 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>
          );
        }
      }
    
    import React,{Component}来自'React';
    const LineChart=require('react-chartjs-2')。行;
    类应用程序扩展组件{
    建造师(道具){
    超级(道具);
    this.chartRef=React.createRef();
    this.chartObject=null;
    }
    componentDidMount(){
    this.chartObject=this.chartRef.current.getContext('2d');
    this.chartObject.update();
    }
    render(){
    报税表(
    );
    }
    }
    
  • 发件人:

    当ref属性用于 自定义类组件,ref对象接收装入的实例 组件的当前状态

    因此,当组件装入时,您将不会收到
    画布,而是收到组件的实例。这就是为什么我认为当App
    componentDidMount
    被调用时,
    LineChart
    尚未装入,这就是为什么
    current
    仍然为空

    再次

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


    将不工作,因为您将接收组件的实例,而不是
    画布

    是否使用React 16.3?是的,我使用的是16.3(16.3.2)