我可以创建一个图表并为mouseOver
事件传递一个函数,该函数只记录我悬停在的标记的x和y值:
// Works
import React from 'react';
import { render } from 'react-dom';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
class App extends React.Component {
render = () => {
const options = {
chart: {
type: 'spline'
},
title: {
text: 'My chart'
},
series: [
{
data: [1, 2, 1, 4, 3, 6]
}
],
plotOptions: {
series: {
point: {
events: {
mouseOver: function () {
const point = { x: this.x, y: this.y };
console.log(point);
}
}
}
}
}
};
return (
<div>
<HighchartsReact highcharts={Highcharts} options={options} />
</div>
)
}
}
render(<App />, document.getElementById('root'));
最终,我希望能够将point
传递回我的组件并在我的应用程序的其他地方使用它。
从事件中调用我的组件中的函数的简单想法不起作用 - 我在this
中传递的plotOptions
不再引用我的组件,而是指向图表中的点:
// Does not work
// Uncaught TypeError: this.handleMouseOver is not a function
import React from 'react';
import { render } from 'react-dom';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
class App extends React.Component {
handleMouseOver = point => {
console.log(`handleMouseOver gets ${point}`);
}
render = () => {
const options = {
chart: {
type: 'spline'
},
title: {
text: 'My chart'
},
series: [
{
data: [1, 2, 1, 4, 3, 6]
}
],
plotOptions: {
series: {
point: {
events: {
mouseOver: function () {
const point = { x: this.x, y: this.y };
this.handleMouseOver(point); <--- not the `this` of my component
}
}
}
}
}
};
return (
<div>
<HighchartsReact highcharts={Highcharts} options={options} />
</div>
)
}
}
render(<App />, document.getElementById('root'));
毫不奇怪,当我将鼠标悬停在一个点上时,我在浏览器中得到的错误是
Uncaught TypeError: this.handleMouseOver is not a function
有什么建议?
谢谢。
您可以使用以下解决方案之一来实现它:
1)保存图表对象中的组件引用,如下所示:
componentDidMount() {
this.chart = this.refs.chart.chart;
this.chart.component = this;
}
并在mouseOver
回调中使用它:
plotOptions: {
series: {
point: {
events: {
mouseOver: function() {
const self = this.series.chart.component;
const point = {
x: this.x,
y: this.y
};
self.handleMouseOver(point);
}
}
}
}
}
演示:
2)使用IIFE保存对组件对象的引用,然后在mouseOver
回调函数中使用它:
plotOptions: {
series: {
point: {
events: {
mouseOver: (function(self) {
return function() {
const point = {
x: this.x,
y: this.y
};
self.handleMouseOver(point);
};
})(this)
}
}
}
}
演示: