【发布时间】:2020-04-28 20:19:51
【问题描述】:
我正在尝试在 React 的简单柱形图中实现一种行为,我可以在其中单击系列点并让 xAxis 标签更改样式。此外,当您再次单击时,应删除该样式。这与我们对鼠标悬停和鼠标移出的行为相同,但对于单击事件。我可以让它处理鼠标事件,但不能处理点击事件。
这有可能实现吗?这是code sample 我有。
【问题讨论】:
标签: reactjs highcharts
我正在尝试在 React 的简单柱形图中实现一种行为,我可以在其中单击系列点并让 xAxis 标签更改样式。此外,当您再次单击时,应删除该样式。这与我们对鼠标悬停和鼠标移出的行为相同,但对于单击事件。我可以让它处理鼠标事件,但不能处理点击事件。
这有可能实现吗?这是code sample 我有。
【问题讨论】:
标签: reactjs highcharts
执行以下操作:
current 用onClick 上的当前轴号更新它的值
config-options 中定义x-Axis 和labels
label 中使用formatter 函数。此函数提供当前轴value 作为参数。使用它并将其与您的 current 状态进行比较并动态调整样式。code sample is here的工作副本
代码片段
class App extends React.Component {
state = {
current: "black"
};
options = {
tooltip: {
enabled: false
},
xAxis: {
labels: {
formatter: item => {
const color = this.state.current === item.value ? "red" : "black";
const fontWeight =
this.state.current === item.value ? "bold" : "normal";
return `<span style="color: ${color}; font-weight: ${fontWeight}">${
item.value
}</span>`;
}
}
},
series: [
{
data: [1, 2, 3, 4],
type: "column",
colors: ["#000000"],
cursor: "pointer",
point: {
events: {
click: (e, x, y) => {
this.setState({ current: e.point.x });
console.log(e.target, e.point.x);
}
// mouseOver: function(e) {
// $(this.series.chart.xAxis[0].labelGroup.element.childNodes[this.x]).css({fontWeight: 'bold'});
// },
// mouseOut: function() {
// $(this.series.chart.xAxis[0].labelGroup.element.childNodes[this.x]).css({fontWeight: 'normal'});
// }
}
}
}
]
};
render() {
return (
<div>
<h2>Highcharts</h2>
<ReactHighcharts config={this.options} />
</div>
);
}
}
【讨论】:
只需使用点击事件函数来改变标签的 CSS 样式。例如:
series: [{
...,
point: {
events: {
click: function() {
var ticks = this.series.xAxis.ticks,
label,
fontWeight;
if (ticks[this.x]) {
label = ticks[this.x].label;
fontWeight = (
label.styles.fontWeight && label.styles.fontWeight === 'bold'
) ? 'normal' : 'bold';
ticks[this.x].label.css({
'fontWeight': fontWeight
});
}
}
}
}
}]
现场演示: http://jsfiddle.net/BlackLabel/6m4e8x0y/4991/
API 参考:
https://api.highcharts.com/highcharts/series.column.events.click
https://api.highcharts.com/class-reference/Highcharts.SVGElement#css
【讨论】: