reactjs组件中的引用为空
我在渲染函数中有一个react-chartjs-2元素,我从react.createRef()为其分配了一个ref,但是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)
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(){
报税表(
);
}
}
画布,而是收到组件的实例。这就是为什么我认为当AppcomponentDidMount
被调用时,LineChart
尚未装入,这就是为什么current
仍然为空
再次
this.chartObject=this.chartRef.current.getContext('2d')代码>
将不工作,因为您将接收组件的实例,而不是画布
是否使用React 16.3?是的,我使用的是16.3(16.3.2)