在highcharts事件加载函数中访问State变量

时间:2018-05-16 13:13:15

标签: react-native highcharts

export class GraphComponent extends React.Component{
    constructor(){
        super();
        this.state={data:[],data20:[]};
    }

    render(){
        var Highcharts='Highcharts';
        let self=this;
        var conf={
            chart: {
                type: 'spline',
                animation: Highcharts.svg,
                marginRight: 10,
                events: {
                    load: function () {
                        var series = this.series[0],i=0,j=1,k=0;
                        var p=self.state.data; // Access State variable here
                    }
                }
            }
            series: [{
            name: 'Random data',
            data: this.state.data20 / Accessible Here
            }]
        }
        return (<ChartView style={{height:300}} config={conf} options={options}></ChartView>);
    }
}

{"data":[{"x":154745486745,"y":0.5} // some 50-60 objects like this]}

我从JSON / SERVER获取这些数据到state.data20(前20个)和state.data(其余的)。 state.data20被绘制。在图表事件加载函数中,state.data不可访问。我尝试了一些方法,但仍然失败了。

With Self reference Image

Without Self reference Image

1 个答案:

答案 0 :(得分:0)

尝试在变量上保存参考号this。看看:

export class GraphComponent extends React.Component{
    constructor(){
        super();
        this.state={data:[],data20:[]};
    }

    render(){
        var Highcharts='Highcharts';

        // Declare a variable to keep a reference to react context
        let self = this;

        var conf={
            chart: {
                type: 'spline',
                animation: Highcharts.svg,
                marginRight: 10,
                events: {
                    load: function () {
                        var series = this.series[0],i=0,j=1,k=0;
                        var p = self.state.data; // Access State variable using self
                    }
                }
            }
        }
        return (<ChartView style={{height:300}} config={conf} options={options}></ChartView>);
    }
}