当用户单击按钮时,我试图动态设置高图的系列数据。我需要highchart的引用,但不确定如何获取引用以调用series [0] .setData函数。
这是我的沙箱。
https://codesandbox.io/s/highcharts-react-demo-rtlie
这里是代码-
import React from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
import drilldow from "highcharts/modules/drilldown";
//import HighchartsReact from "./HighchartsReact.js";
import PieChart from "highcharts-react-official";
drilldow(Highcharts);
const options = {
chart: {
type: "pie"
},
series: [
{
data: [{ y: 100, name: "Female" }, { y: 50, name: "Male" }]
}
]
};
class App extends React.Component {
constructor() {
super();
this.state = {
chart_options: null
};
console.log(this.state);
}
onFilterClickHandler = () => {
console.log("onfilterclickhandler");
// need chart reference to call the series.setdata function
//chart.series[0].setData
};
render() {
const key = 1;
return (
<div>
<div>
<label>
For female click here
<input
type="checkbox"
value={key}
onClick={this.onFilterClickHandler}
/>
</label>
</div>
<h2>Highcharts</h2>
<PieChart highcharts={Highcharts} options={options} />
</div>
);
}
}
render(<App />, document.getElementById("root"));
您可以通过setState
方法更改系列数据:
onFilterClickHandler = () => {
this.setState({
chart_options: {
series: [
{
data: [...]
}
]
}
});
};
实时示例: https://codesandbox.io/s/highcharts-react-demo-wd9m1
或获取图表参考并直接通过一系列调用setData
:
class App extends React.Component {
constructor() {
...
this.afterChartCreated = this.afterChartCreated.bind(this);
}
afterChartCreated(chart) {
this.internalChart = chart;
}
onFilterClickHandler = () => {
...
this.internalChart.series[0].setData([50, 50]);
};
render() {
const key = 1;
return (
<div>
...
<PieChart
highcharts={Highcharts}
options={options}
callback={this.afterChartCreated}
/>
</div>
);
}
}
实时演示: https://codesandbox.io/s/highcharts-react-demo-c8yvg
文档: https://github.com/highcharts/highcharts-react#how-to-get-a-chart-instance