gpt4 book ai didi

javascript - 如何将 Highcharts 事件回调(click、mouseOver、mouseOut)中的值传回 React 组件成员函数?

转载 作者:行者123 更新时间:2023-11-29 23:02:33 26 4
gpt4 key购买 nike

我可以创建一个图表并为 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'));

最终我希望能够将该传递回我的组件并在我的应用程序的其他地方使用它。

从事件中调用我的组件中的函数的简单想法不起作用——我在 plotOptions 中传递的 this 不再引用我的组件但就图表中的点而言:

// 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)
}
}
}
}

演示:

关于javascript - 如何将 Highcharts 事件回调(click、mouseOver、mouseOut)中的值传回 React 组件成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com